code
stringlengths
38
801k
repo_path
stringlengths
6
263
pub const CRYTPDLG_FLAGS_MASK = @as(u32, 4278190080); pub const CRYPTDLG_REVOCATION_DEFAULT = @as(u32, 0); pub const CRYPTDLG_REVOCATION_ONLINE = @as(u32, 2147483648); pub const CRYPTDLG_REVOCATION_CACHE = @as(u32, 1073741824); pub const CRYPTDLG_REVOCATION_NONE = @as(u32, 536870912); pub const CRYPTDLG_CACHE_ONLY_URL_RETRIEVAL = @as(u32, 268435456); pub const CRYPTDLG_DISABLE_AIA = @as(u32, 134217728); pub const CRYPTDLG_POLICY_MASK = @as(u32, 65535); pub const POLICY_IGNORE_NON_CRITICAL_BC = @as(u32, 1); pub const CRYPTDLG_ACTION_MASK = @as(u32, 4294901760); pub const ACTION_REVOCATION_DEFAULT_ONLINE = @as(u32, 65536); pub const ACTION_REVOCATION_DEFAULT_CACHE = @as(u32, 131072); pub const CERT_DISPWELL_SELECT = @as(u32, 1); pub const CERT_DISPWELL_TRUST_CA_CERT = @as(u32, 2); pub const CERT_DISPWELL_TRUST_LEAF_CERT = @as(u32, 3); pub const CERT_DISPWELL_TRUST_ADD_CA_CERT = @as(u32, 4); pub const CERT_DISPWELL_TRUST_ADD_LEAF_CERT = @as(u32, 5); pub const CERT_DISPWELL_DISTRUST_CA_CERT = @as(u32, 6); pub const CERT_DISPWELL_DISTRUST_LEAF_CERT = @as(u32, 7); pub const CERT_DISPWELL_DISTRUST_ADD_CA_CERT = @as(u32, 8); pub const CERT_DISPWELL_DISTRUST_ADD_LEAF_CERT = @as(u32, 9); pub const CSS_SELECTCERT_MASK = @as(u32, 16777215); pub const SELCERT_PROPERTIES = @as(u32, 100); pub const SELCERT_FINEPRINT = @as(u32, 101); pub const SELCERT_CERTLIST = @as(u32, 102); pub const SELCERT_ISSUED_TO = @as(u32, 103); pub const SELCERT_VALIDITY = @as(u32, 104); pub const SELCERT_ALGORITHM = @as(u32, 105); pub const SELCERT_SERIAL_NUM = @as(u32, 106); pub const SELCERT_THUMBPRINT = @as(u32, 107); pub const CM_VIEWFLAGS_MASK = @as(u32, 16777215); pub const CERTVIEW_CRYPTUI_LPARAM = @as(u32, 8388608); pub const CERT_FILTER_OP_EXISTS = @as(u32, 1); pub const CERT_FILTER_OP_NOT_EXISTS = @as(u32, 2); pub const CERT_FILTER_OP_EQUALITY = @as(u32, 3); pub const CERT_FILTER_INCLUDE_V1_CERTS = @as(u32, 1); pub const CERT_FILTER_VALID_TIME_RANGE = @as(u32, 2); pub const CERT_FILTER_VALID_SIGNATURE = @as(u32, 4); pub const CERT_FILTER_LEAF_CERTS_ONLY = @as(u32, 8); pub const CERT_FILTER_ISSUER_CERTS_ONLY = @as(u32, 16); pub const CERT_FILTER_KEY_EXISTS = @as(u32, 32); pub const CERT_VALIDITY_BEFORE_START = @as(u32, 1); pub const CERT_VALIDITY_AFTER_END = @as(u32, 2); pub const CERT_VALIDITY_SIGNATURE_FAILS = @as(u32, 4); pub const CERT_VALIDITY_CERTIFICATE_REVOKED = @as(u32, 8); pub const CERT_VALIDITY_KEY_USAGE_EXT_FAILURE = @as(u32, 16); pub const CERT_VALIDITY_EXTENDED_USAGE_FAILURE = @as(u32, 32); pub const CERT_VALIDITY_NAME_CONSTRAINTS_FAILURE = @as(u32, 64); pub const CERT_VALIDITY_UNKNOWN_CRITICAL_EXTENSION = @as(u32, 128); pub const CERT_VALIDITY_ISSUER_INVALID = @as(u32, 256); pub const CERT_VALIDITY_OTHER_EXTENSION_FAILURE = @as(u32, 512); pub const CERT_VALIDITY_PERIOD_NESTING_FAILURE = @as(u32, 1024); pub const CERT_VALIDITY_OTHER_ERROR = @as(u32, 2048); pub const CERT_VALIDITY_ISSUER_DISTRUST = @as(u32, 33554432); pub const CERT_VALIDITY_EXPLICITLY_DISTRUSTED = @as(u32, 16777216); pub const CERT_VALIDITY_NO_ISSUER_CERT_FOUND = @as(u32, 268435456); pub const CERT_VALIDITY_NO_CRL_FOUND = @as(u32, 536870912); pub const CERT_VALIDITY_CRL_OUT_OF_DATE = @as(u32, 1073741824); pub const CERT_VALIDITY_NO_TRUST_DATA = @as(u32, 2147483648); pub const CERT_VALIDITY_MASK_TRUST = @as(u32, 4294901760); pub const CERT_VALIDITY_MASK_VALIDITY = @as(u32, 65535); pub const CERT_TRUST_MASK = @as(u32, 16777215); pub const CERT_TRUST_DO_FULL_SEARCH = @as(u32, 1); pub const CERT_TRUST_PERMIT_MISSING_CRLS = @as(u32, 2); pub const CERT_TRUST_DO_FULL_TRUST = @as(u32, 5); pub const CERT_CREDENTIAL_PROVIDER_ID = @as(i32, -509); pub const CRYPTUI_SELECT_ISSUEDTO_COLUMN = @as(u64, 1); pub const CRYPTUI_SELECT_ISSUEDBY_COLUMN = @as(u64, 2); pub const CRYPTUI_SELECT_INTENDEDUSE_COLUMN = @as(u64, 4); pub const CRYPTUI_SELECT_FRIENDLYNAME_COLUMN = @as(u64, 8); pub const CRYPTUI_SELECT_LOCATION_COLUMN = @as(u64, 16); pub const CRYPTUI_SELECT_EXPIRATION_COLUMN = @as(u64, 32); pub const CRYPTUI_CERT_MGR_TAB_MASK = @as(u32, 15); pub const CRYPTUI_CERT_MGR_PUBLISHER_TAB = @as(u32, 4); pub const CRYPTUI_CERT_MGR_SINGLE_TAB_FLAG = @as(u32, 32768); pub const CRYPTUI_WIZ_DIGITAL_SIGN_EXCLUDE_PAGE_HASHES = @as(u32, 2); pub const CRYPTUI_WIZ_DIGITAL_SIGN_INCLUDE_PAGE_HASHES = @as(u32, 4); pub const CRYPTUI_WIZ_EXPORT_FORMAT_SERIALIZED_CERT_STORE = @as(u32, 5); //-------------------------------------------------------------------------------- // Section: Types (40) //-------------------------------------------------------------------------------- pub const CRYPTUI_WIZ_FLAGS = enum(u32) { NO_UI = 1, IGNORE_NO_UI_FLAG_FOR_CSPS = 2, NO_UI_EXCEPT_CSP = 3, IMPORT_ALLOW_CERT = 131072, IMPORT_ALLOW_CRL = 262144, IMPORT_ALLOW_CTL = 524288, IMPORT_NO_CHANGE_DEST_STORE = 65536, IMPORT_TO_LOCALMACHINE = 1048576, IMPORT_TO_CURRENTUSER = 2097152, IMPORT_REMOTE_DEST_STORE = 4194304, EXPORT_PRIVATE_KEY = 256, EXPORT_NO_DELETE_PRIVATE_KEY = 512, _, pub fn initFlags(o: struct { NO_UI: u1 = 0, IGNORE_NO_UI_FLAG_FOR_CSPS: u1 = 0, NO_UI_EXCEPT_CSP: u1 = 0, IMPORT_ALLOW_CERT: u1 = 0, IMPORT_ALLOW_CRL: u1 = 0, IMPORT_ALLOW_CTL: u1 = 0, IMPORT_NO_CHANGE_DEST_STORE: u1 = 0, IMPORT_TO_LOCALMACHINE: u1 = 0, IMPORT_TO_CURRENTUSER: u1 = 0, IMPORT_REMOTE_DEST_STORE: u1 = 0, EXPORT_PRIVATE_KEY: u1 = 0, EXPORT_NO_DELETE_PRIVATE_KEY: u1 = 0, }) CRYPTUI_WIZ_FLAGS { return @intToEnum(CRYPTUI_WIZ_FLAGS, (if (o.NO_UI == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.NO_UI) else 0) | (if (o.IGNORE_NO_UI_FLAG_FOR_CSPS == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IGNORE_NO_UI_FLAG_FOR_CSPS) else 0) | (if (o.NO_UI_EXCEPT_CSP == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.NO_UI_EXCEPT_CSP) else 0) | (if (o.IMPORT_ALLOW_CERT == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IMPORT_ALLOW_CERT) else 0) | (if (o.IMPORT_ALLOW_CRL == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IMPORT_ALLOW_CRL) else 0) | (if (o.IMPORT_ALLOW_CTL == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IMPORT_ALLOW_CTL) else 0) | (if (o.IMPORT_NO_CHANGE_DEST_STORE == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IMPORT_NO_CHANGE_DEST_STORE) else 0) | (if (o.IMPORT_TO_LOCALMACHINE == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IMPORT_TO_LOCALMACHINE) else 0) | (if (o.IMPORT_TO_CURRENTUSER == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IMPORT_TO_CURRENTUSER) else 0) | (if (o.IMPORT_REMOTE_DEST_STORE == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.IMPORT_REMOTE_DEST_STORE) else 0) | (if (o.EXPORT_PRIVATE_KEY == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.EXPORT_PRIVATE_KEY) else 0) | (if (o.EXPORT_NO_DELETE_PRIVATE_KEY == 1) @enumToInt(CRYPTUI_WIZ_FLAGS.EXPORT_NO_DELETE_PRIVATE_KEY) else 0) ); } }; pub const CRYPTUI_WIZ_NO_UI = CRYPTUI_WIZ_FLAGS.NO_UI; pub const CRYPTUI_WIZ_IGNORE_NO_UI_FLAG_FOR_CSPS = CRYPTUI_WIZ_FLAGS.IGNORE_NO_UI_FLAG_FOR_CSPS; pub const CRYPTUI_WIZ_NO_UI_EXCEPT_CSP = CRYPTUI_WIZ_FLAGS.NO_UI_EXCEPT_CSP; pub const CRYPTUI_WIZ_IMPORT_ALLOW_CERT = CRYPTUI_WIZ_FLAGS.IMPORT_ALLOW_CERT; pub const CRYPTUI_WIZ_IMPORT_ALLOW_CRL = CRYPTUI_WIZ_FLAGS.IMPORT_ALLOW_CRL; pub const CRYPTUI_WIZ_IMPORT_ALLOW_CTL = CRYPTUI_WIZ_FLAGS.IMPORT_ALLOW_CTL; pub const CRYPTUI_WIZ_IMPORT_NO_CHANGE_DEST_STORE = CRYPTUI_WIZ_FLAGS.IMPORT_NO_CHANGE_DEST_STORE; pub const CRYPTUI_WIZ_IMPORT_TO_LOCALMACHINE = CRYPTUI_WIZ_FLAGS.IMPORT_TO_LOCALMACHINE; pub const CRYPTUI_WIZ_IMPORT_TO_CURRENTUSER = CRYPTUI_WIZ_FLAGS.IMPORT_TO_CURRENTUSER; pub const CRYPTUI_WIZ_IMPORT_REMOTE_DEST_STORE = CRYPTUI_WIZ_FLAGS.IMPORT_REMOTE_DEST_STORE; pub const CRYPTUI_WIZ_EXPORT_PRIVATE_KEY = CRYPTUI_WIZ_FLAGS.EXPORT_PRIVATE_KEY; pub const CRYPTUI_WIZ_EXPORT_NO_DELETE_PRIVATE_KEY = CRYPTUI_WIZ_FLAGS.EXPORT_NO_DELETE_PRIVATE_KEY; pub const CRYPTUI_VIEWCERTIFICATE_FLAGS = enum(u32) { HIDE_HIERARCHYPAGE = 1, HIDE_DETAILPAGE = 2, DISABLE_EDITPROPERTIES = 4, ENABLE_EDITPROPERTIES = 8, DISABLE_ADDTOSTORE = 16, ENABLE_ADDTOSTORE = 32, ACCEPT_DECLINE_STYLE = 64, IGNORE_UNTRUSTED_ROOT = 128, DONT_OPEN_STORES = 256, ONLY_OPEN_ROOT_STORE = 512, WARN_UNTRUSTED_ROOT = 1024, ENABLE_REVOCATION_CHECKING = 2048, WARN_REMOTE_TRUST = 4096, DISABLE_EXPORT = 8192, ENABLE_REVOCATION_CHECK_END_CERT = 16384, ENABLE_REVOCATION_CHECK_CHAIN = 32768, // ENABLE_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 2048, this enum value conflicts with ENABLE_REVOCATION_CHECKING DISABLE_HTMLLINK = 65536, DISABLE_ISSUERSTATEMENT = 131072, CACHE_ONLY_URL_RETRIEVAL = 262144, _, pub fn initFlags(o: struct { HIDE_HIERARCHYPAGE: u1 = 0, HIDE_DETAILPAGE: u1 = 0, DISABLE_EDITPROPERTIES: u1 = 0, ENABLE_EDITPROPERTIES: u1 = 0, DISABLE_ADDTOSTORE: u1 = 0, ENABLE_ADDTOSTORE: u1 = 0, ACCEPT_DECLINE_STYLE: u1 = 0, IGNORE_UNTRUSTED_ROOT: u1 = 0, DONT_OPEN_STORES: u1 = 0, ONLY_OPEN_ROOT_STORE: u1 = 0, WARN_UNTRUSTED_ROOT: u1 = 0, ENABLE_REVOCATION_CHECKING: u1 = 0, WARN_REMOTE_TRUST: u1 = 0, DISABLE_EXPORT: u1 = 0, ENABLE_REVOCATION_CHECK_END_CERT: u1 = 0, ENABLE_REVOCATION_CHECK_CHAIN: u1 = 0, DISABLE_HTMLLINK: u1 = 0, DISABLE_ISSUERSTATEMENT: u1 = 0, CACHE_ONLY_URL_RETRIEVAL: u1 = 0, }) CRYPTUI_VIEWCERTIFICATE_FLAGS { return @intToEnum(CRYPTUI_VIEWCERTIFICATE_FLAGS, (if (o.HIDE_HIERARCHYPAGE == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.HIDE_HIERARCHYPAGE) else 0) | (if (o.HIDE_DETAILPAGE == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.HIDE_DETAILPAGE) else 0) | (if (o.DISABLE_EDITPROPERTIES == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_EDITPROPERTIES) else 0) | (if (o.ENABLE_EDITPROPERTIES == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_EDITPROPERTIES) else 0) | (if (o.DISABLE_ADDTOSTORE == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_ADDTOSTORE) else 0) | (if (o.ENABLE_ADDTOSTORE == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_ADDTOSTORE) else 0) | (if (o.ACCEPT_DECLINE_STYLE == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.ACCEPT_DECLINE_STYLE) else 0) | (if (o.IGNORE_UNTRUSTED_ROOT == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.IGNORE_UNTRUSTED_ROOT) else 0) | (if (o.DONT_OPEN_STORES == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.DONT_OPEN_STORES) else 0) | (if (o.ONLY_OPEN_ROOT_STORE == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.ONLY_OPEN_ROOT_STORE) else 0) | (if (o.WARN_UNTRUSTED_ROOT == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.WARN_UNTRUSTED_ROOT) else 0) | (if (o.ENABLE_REVOCATION_CHECKING == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_REVOCATION_CHECKING) else 0) | (if (o.WARN_REMOTE_TRUST == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.WARN_REMOTE_TRUST) else 0) | (if (o.DISABLE_EXPORT == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_EXPORT) else 0) | (if (o.ENABLE_REVOCATION_CHECK_END_CERT == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_REVOCATION_CHECK_END_CERT) else 0) | (if (o.ENABLE_REVOCATION_CHECK_CHAIN == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_REVOCATION_CHECK_CHAIN) else 0) | (if (o.DISABLE_HTMLLINK == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_HTMLLINK) else 0) | (if (o.DISABLE_ISSUERSTATEMENT == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_ISSUERSTATEMENT) else 0) | (if (o.CACHE_ONLY_URL_RETRIEVAL == 1) @enumToInt(CRYPTUI_VIEWCERTIFICATE_FLAGS.CACHE_ONLY_URL_RETRIEVAL) else 0) ); } }; pub const CRYPTUI_HIDE_HIERARCHYPAGE = CRYPTUI_VIEWCERTIFICATE_FLAGS.HIDE_HIERARCHYPAGE; pub const CRYPTUI_HIDE_DETAILPAGE = CRYPTUI_VIEWCERTIFICATE_FLAGS.HIDE_DETAILPAGE; pub const CRYPTUI_DISABLE_EDITPROPERTIES = CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_EDITPROPERTIES; pub const CRYPTUI_ENABLE_EDITPROPERTIES = CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_EDITPROPERTIES; pub const CRYPTUI_DISABLE_ADDTOSTORE = CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_ADDTOSTORE; pub const CRYPTUI_ENABLE_ADDTOSTORE = CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_ADDTOSTORE; pub const CRYPTUI_ACCEPT_DECLINE_STYLE = CRYPTUI_VIEWCERTIFICATE_FLAGS.ACCEPT_DECLINE_STYLE; pub const CRYPTUI_IGNORE_UNTRUSTED_ROOT = CRYPTUI_VIEWCERTIFICATE_FLAGS.IGNORE_UNTRUSTED_ROOT; pub const CRYPTUI_DONT_OPEN_STORES = CRYPTUI_VIEWCERTIFICATE_FLAGS.DONT_OPEN_STORES; pub const CRYPTUI_ONLY_OPEN_ROOT_STORE = CRYPTUI_VIEWCERTIFICATE_FLAGS.ONLY_OPEN_ROOT_STORE; pub const CRYPTUI_WARN_UNTRUSTED_ROOT = CRYPTUI_VIEWCERTIFICATE_FLAGS.WARN_UNTRUSTED_ROOT; pub const CRYPTUI_ENABLE_REVOCATION_CHECKING = CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_REVOCATION_CHECKING; pub const CRYPTUI_WARN_REMOTE_TRUST = CRYPTUI_VIEWCERTIFICATE_FLAGS.WARN_REMOTE_TRUST; pub const CRYPTUI_DISABLE_EXPORT = CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_EXPORT; pub const CRYPTUI_ENABLE_REVOCATION_CHECK_END_CERT = CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_REVOCATION_CHECK_END_CERT; pub const CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN = CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_REVOCATION_CHECK_CHAIN; pub const CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = CRYPTUI_VIEWCERTIFICATE_FLAGS.ENABLE_REVOCATION_CHECKING; pub const CRYPTUI_DISABLE_HTMLLINK = CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_HTMLLINK; pub const CRYPTUI_DISABLE_ISSUERSTATEMENT = CRYPTUI_VIEWCERTIFICATE_FLAGS.DISABLE_ISSUERSTATEMENT; pub const CRYPTUI_CACHE_ONLY_URL_RETRIEVAL = CRYPTUI_VIEWCERTIFICATE_FLAGS.CACHE_ONLY_URL_RETRIEVAL; pub const CERT_SELECT_STRUCT_FLAGS = enum(u32) { HIDE_PROPERTIES = 1, ENABLEHOOK = 2, ALLOWMULTISELECT = 4, SHOW_HELP = 16, ENABLETEMPLATE = 32, ENABLETEMPLATEHANDLE = 64, _, pub fn initFlags(o: struct { HIDE_PROPERTIES: u1 = 0, ENABLEHOOK: u1 = 0, ALLOWMULTISELECT: u1 = 0, SHOW_HELP: u1 = 0, ENABLETEMPLATE: u1 = 0, ENABLETEMPLATEHANDLE: u1 = 0, }) CERT_SELECT_STRUCT_FLAGS { return @intToEnum(CERT_SELECT_STRUCT_FLAGS, (if (o.HIDE_PROPERTIES == 1) @enumToInt(CERT_SELECT_STRUCT_FLAGS.HIDE_PROPERTIES) else 0) | (if (o.ENABLEHOOK == 1) @enumToInt(CERT_SELECT_STRUCT_FLAGS.ENABLEHOOK) else 0) | (if (o.ALLOWMULTISELECT == 1) @enumToInt(CERT_SELECT_STRUCT_FLAGS.ALLOWMULTISELECT) else 0) | (if (o.SHOW_HELP == 1) @enumToInt(CERT_SELECT_STRUCT_FLAGS.SHOW_HELP) else 0) | (if (o.ENABLETEMPLATE == 1) @enumToInt(CERT_SELECT_STRUCT_FLAGS.ENABLETEMPLATE) else 0) | (if (o.ENABLETEMPLATEHANDLE == 1) @enumToInt(CERT_SELECT_STRUCT_FLAGS.ENABLETEMPLATEHANDLE) else 0) ); } }; pub const CSS_HIDE_PROPERTIES = CERT_SELECT_STRUCT_FLAGS.HIDE_PROPERTIES; pub const CSS_ENABLEHOOK = CERT_SELECT_STRUCT_FLAGS.ENABLEHOOK; pub const CSS_ALLOWMULTISELECT = CERT_SELECT_STRUCT_FLAGS.ALLOWMULTISELECT; pub const CSS_SHOW_HELP = CERT_SELECT_STRUCT_FLAGS.SHOW_HELP; pub const CSS_ENABLETEMPLATE = CERT_SELECT_STRUCT_FLAGS.ENABLETEMPLATE; pub const CSS_ENABLETEMPLATEHANDLE = CERT_SELECT_STRUCT_FLAGS.ENABLETEMPLATEHANDLE; pub const CRYPTUI_WIZ_IMPORT_SUBJECT_OPTION = enum(u32) { FILE = 1, CERT_CONTEXT = 2, CTL_CONTEXT = 3, CRL_CONTEXT = 4, CERT_STORE = 5, }; pub const CRYPTUI_WIZ_IMPORT_SUBJECT_FILE = CRYPTUI_WIZ_IMPORT_SUBJECT_OPTION.FILE; pub const CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_CONTEXT = CRYPTUI_WIZ_IMPORT_SUBJECT_OPTION.CERT_CONTEXT; pub const CRYPTUI_WIZ_IMPORT_SUBJECT_CTL_CONTEXT = CRYPTUI_WIZ_IMPORT_SUBJECT_OPTION.CTL_CONTEXT; pub const CRYPTUI_WIZ_IMPORT_SUBJECT_CRL_CONTEXT = CRYPTUI_WIZ_IMPORT_SUBJECT_OPTION.CRL_CONTEXT; pub const CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE = CRYPTUI_WIZ_IMPORT_SUBJECT_OPTION.CERT_STORE; pub const CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT = enum(u32) { BLOB = 2, FILE = 1, NONE = 0, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_BLOB = CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT.BLOB; pub const CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE = CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT.FILE; pub const CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_NONE = CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT.NONE; pub const CRYPTUI_WIZ_DIGITAL_SIGN = enum(u32) { CERT = 1, STORE = 2, PVK = 3, NONE = 0, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_CERT = CRYPTUI_WIZ_DIGITAL_SIGN.CERT; pub const CRYPTUI_WIZ_DIGITAL_SIGN_STORE = CRYPTUI_WIZ_DIGITAL_SIGN.STORE; pub const CRYPTUI_WIZ_DIGITAL_SIGN_PVK = CRYPTUI_WIZ_DIGITAL_SIGN.PVK; pub const CRYPTUI_WIZ_DIGITAL_SIGN_NONE = CRYPTUI_WIZ_DIGITAL_SIGN.NONE; pub const CRYPTUI_WIZ_EXPORT_SUBJECT = enum(u32) { ERT_CONTEXT = 1, TL_CONTEXT = 2, RL_CONTEXT = 3, ERT_STORE = 4, ERT_STORE_CERTIFICATES_ONLY = 5, }; pub const CRYPTUI_WIZ_EXPORT_CERT_CONTEXT = CRYPTUI_WIZ_EXPORT_SUBJECT.ERT_CONTEXT; pub const CRYPTUI_WIZ_EXPORT_CTL_CONTEXT = CRYPTUI_WIZ_EXPORT_SUBJECT.TL_CONTEXT; pub const CRYPTUI_WIZ_EXPORT_CRL_CONTEXT = CRYPTUI_WIZ_EXPORT_SUBJECT.RL_CONTEXT; pub const CRYPTUI_WIZ_EXPORT_CERT_STORE = CRYPTUI_WIZ_EXPORT_SUBJECT.ERT_STORE; pub const CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY = CRYPTUI_WIZ_EXPORT_SUBJECT.ERT_STORE_CERTIFICATES_ONLY; pub const CRYPTUI_WIZ_DIGITAL_SIGN_SIG_TYPE = enum(u32) { COMMERCIAL = 1, INDIVIDUAL = 2, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_COMMERCIAL = CRYPTUI_WIZ_DIGITAL_SIGN_SIG_TYPE.COMMERCIAL; pub const CRYPTUI_WIZ_DIGITAL_SIGN_INDIVIDUAL = CRYPTUI_WIZ_DIGITAL_SIGN_SIG_TYPE.INDIVIDUAL; pub const CRYPTUI_WIZ_DIGITAL_SIGN_PVK_OPTION = enum(u32) { FILE = 1, PROV = 2, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_PVK_FILE = CRYPTUI_WIZ_DIGITAL_SIGN_PVK_OPTION.FILE; pub const CRYPTUI_WIZ_DIGITAL_SIGN_PVK_PROV = CRYPTUI_WIZ_DIGITAL_SIGN_PVK_OPTION.PROV; pub const CERT_VIEWPROPERTIES_STRUCT_FLAGS = enum(u32) { ENABLEHOOK = 1, SHOW_HELP = 2, SHOW_HELPICON = 4, ENABLETEMPLATE = 8, HIDE_ADVANCEPAGE = 16, HIDE_TRUSTPAGE = 32, NO_NAMECHANGE = 64, NO_EDITTRUST = 128, HIDE_DETAILPAGE = 256, ADD_CERT_STORES = 512, _, pub fn initFlags(o: struct { ENABLEHOOK: u1 = 0, SHOW_HELP: u1 = 0, SHOW_HELPICON: u1 = 0, ENABLETEMPLATE: u1 = 0, HIDE_ADVANCEPAGE: u1 = 0, HIDE_TRUSTPAGE: u1 = 0, NO_NAMECHANGE: u1 = 0, NO_EDITTRUST: u1 = 0, HIDE_DETAILPAGE: u1 = 0, ADD_CERT_STORES: u1 = 0, }) CERT_VIEWPROPERTIES_STRUCT_FLAGS { return @intToEnum(CERT_VIEWPROPERTIES_STRUCT_FLAGS, (if (o.ENABLEHOOK == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLEHOOK) else 0) | (if (o.SHOW_HELP == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELP) else 0) | (if (o.SHOW_HELPICON == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELPICON) else 0) | (if (o.ENABLETEMPLATE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLETEMPLATE) else 0) | (if (o.HIDE_ADVANCEPAGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_ADVANCEPAGE) else 0) | (if (o.HIDE_TRUSTPAGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_TRUSTPAGE) else 0) | (if (o.NO_NAMECHANGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_NAMECHANGE) else 0) | (if (o.NO_EDITTRUST == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_EDITTRUST) else 0) | (if (o.HIDE_DETAILPAGE == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_DETAILPAGE) else 0) | (if (o.ADD_CERT_STORES == 1) @enumToInt(CERT_VIEWPROPERTIES_STRUCT_FLAGS.ADD_CERT_STORES) else 0) ); } }; pub const CM_ENABLEHOOK = CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLEHOOK; pub const CM_SHOW_HELP = CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELP; pub const CM_SHOW_HELPICON = CERT_VIEWPROPERTIES_STRUCT_FLAGS.SHOW_HELPICON; pub const CM_ENABLETEMPLATE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.ENABLETEMPLATE; pub const CM_HIDE_ADVANCEPAGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_ADVANCEPAGE; pub const CM_HIDE_TRUSTPAGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_TRUSTPAGE; pub const CM_NO_NAMECHANGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_NAMECHANGE; pub const CM_NO_EDITTRUST = CERT_VIEWPROPERTIES_STRUCT_FLAGS.NO_EDITTRUST; pub const CM_HIDE_DETAILPAGE = CERT_VIEWPROPERTIES_STRUCT_FLAGS.HIDE_DETAILPAGE; pub const CM_ADD_CERT_STORES = CERT_VIEWPROPERTIES_STRUCT_FLAGS.ADD_CERT_STORES; pub const CRYPTUI_WIZ_EXPORT_FORMAT = enum(u32) { DER = 1, PFX = 2, PKCS7 = 3, BASE64 = 4, CRL = 6, CTL = 7, }; pub const CRYPTUI_WIZ_EXPORT_FORMAT_DER = CRYPTUI_WIZ_EXPORT_FORMAT.DER; pub const CRYPTUI_WIZ_EXPORT_FORMAT_PFX = CRYPTUI_WIZ_EXPORT_FORMAT.PFX; pub const CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7 = CRYPTUI_WIZ_EXPORT_FORMAT.PKCS7; pub const CRYPTUI_WIZ_EXPORT_FORMAT_BASE64 = CRYPTUI_WIZ_EXPORT_FORMAT.BASE64; pub const CRYPTUI_WIZ_EXPORT_FORMAT_CRL = CRYPTUI_WIZ_EXPORT_FORMAT.CRL; pub const CRYPTUI_WIZ_EXPORT_FORMAT_CTL = CRYPTUI_WIZ_EXPORT_FORMAT.CTL; pub const CRYPTUI_WIZ_DIGITAL_ADDITIONAL_CERT_CHOICE = enum(u32) { CHAIN = 1, CHAIN_NO_ROOT = 2, NONE = 0, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN = CRYPTUI_WIZ_DIGITAL_ADDITIONAL_CERT_CHOICE.CHAIN; pub const CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN_NO_ROOT = CRYPTUI_WIZ_DIGITAL_ADDITIONAL_CERT_CHOICE.CHAIN_NO_ROOT; pub const CRYPTUI_WIZ_DIGITAL_SIGN_ADD_NONE = CRYPTUI_WIZ_DIGITAL_ADDITIONAL_CERT_CHOICE.NONE; pub const CTL_MODIFY_REQUEST_OPERATION = enum(u32) { ADD_TRUSTED = 3, ADD_NOT_TRUSTED = 1, REMOVE = 2, }; pub const CTL_MODIFY_REQUEST_ADD_TRUSTED = CTL_MODIFY_REQUEST_OPERATION.ADD_TRUSTED; pub const CTL_MODIFY_REQUEST_ADD_NOT_TRUSTED = CTL_MODIFY_REQUEST_OPERATION.ADD_NOT_TRUSTED; pub const CTL_MODIFY_REQUEST_REMOVE = CTL_MODIFY_REQUEST_OPERATION.REMOVE; pub const PFNCMFILTERPROC = fn( pCertContext: ?*const CERT_CONTEXT, param1: LPARAM, param2: u32, param3: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFNCMHOOKPROC = fn( hwndDialog: ?HWND, message: u32, wParam: WPARAM, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) u32; pub const CERT_SELECT_STRUCT_A = extern struct { dwSize: u32, hwndParent: ?HWND, hInstance: ?HINSTANCE, pTemplateName: ?[*:0]const u8, dwFlags: CERT_SELECT_STRUCT_FLAGS, szTitle: ?[*:0]const u8, cCertStore: u32, arrayCertStore: ?*?*anyopaque, szPurposeOid: ?[*:0]const u8, cCertContext: u32, arrayCertContext: ?*?*CERT_CONTEXT, lCustData: LPARAM, pfnHook: ?PFNCMHOOKPROC, pfnFilter: ?PFNCMFILTERPROC, szHelpFileName: ?[*:0]const u8, dwHelpId: u32, hprov: usize, }; pub const CERT_SELECT_STRUCT_W = extern struct { dwSize: u32, hwndParent: ?HWND, hInstance: ?HINSTANCE, pTemplateName: ?[*:0]const u16, dwFlags: CERT_SELECT_STRUCT_FLAGS, szTitle: ?[*:0]const u16, cCertStore: u32, arrayCertStore: ?*?*anyopaque, szPurposeOid: ?[*:0]const u8, cCertContext: u32, arrayCertContext: ?*?*CERT_CONTEXT, lCustData: LPARAM, pfnHook: ?PFNCMHOOKPROC, pfnFilter: ?PFNCMFILTERPROC, szHelpFileName: ?[*:0]const u16, dwHelpId: u32, hprov: usize, }; pub const CERT_VIEWPROPERTIES_STRUCT_A = extern struct { dwSize: u32, hwndParent: ?HWND, hInstance: ?HINSTANCE, dwFlags: CERT_VIEWPROPERTIES_STRUCT_FLAGS, szTitle: ?[*:0]const u8, pCertContext: ?*const CERT_CONTEXT, arrayPurposes: ?*?PSTR, cArrayPurposes: u32, cRootStores: u32, rghstoreRoots: ?*?*anyopaque, cStores: u32, rghstoreCAs: ?*?*anyopaque, cTrustStores: u32, rghstoreTrust: ?*?*anyopaque, hprov: usize, lCustData: LPARAM, dwPad: u32, szHelpFileName: ?[*:0]const u8, dwHelpId: u32, nStartPage: u32, cArrayPropSheetPages: u32, arrayPropSheetPages: ?*PROPSHEETPAGEA, }; pub const CERT_VIEWPROPERTIES_STRUCT_W = extern struct { dwSize: u32, hwndParent: ?HWND, hInstance: ?HINSTANCE, dwFlags: CERT_VIEWPROPERTIES_STRUCT_FLAGS, szTitle: ?[*:0]const u16, pCertContext: ?*const CERT_CONTEXT, arrayPurposes: ?*?PSTR, cArrayPurposes: u32, cRootStores: u32, rghstoreRoots: ?*?*anyopaque, cStores: u32, rghstoreCAs: ?*?*anyopaque, cTrustStores: u32, rghstoreTrust: ?*?*anyopaque, hprov: usize, lCustData: LPARAM, dwPad: u32, szHelpFileName: ?[*:0]const u16, dwHelpId: u32, nStartPage: u32, cArrayPropSheetPages: u32, arrayPropSheetPages: ?*PROPSHEETPAGEA, }; pub const CMOID = extern struct { szExtensionOID: ?[*:0]const u8, dwTestOperation: u32, pbTestData: ?*u8, cbTestData: u32, }; pub const CMFLTR = extern struct { dwSize: u32, cExtensionChecks: u32, arrayExtensionChecks: ?*CMOID, dwCheckingFlags: u32, }; pub const PFNTRUSTHELPER = fn( pCertContext: ?*const CERT_CONTEXT, lCustData: LPARAM, fLeafCertificate: BOOL, pbTrustBlob: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const CERT_VERIFY_CERTIFICATE_TRUST = extern struct { cbSize: u32, pccert: ?*const CERT_CONTEXT, dwFlags: u32, dwIgnoreErr: u32, pdwErrors: ?*u32, pszUsageOid: ?PSTR, hprov: usize, cRootStores: u32, rghstoreRoots: ?*?*anyopaque, cStores: u32, rghstoreCAs: ?*?*anyopaque, cTrustStores: u32, rghstoreTrust: ?*?*anyopaque, lCustData: LPARAM, pfnTrustHelper: ?PFNTRUSTHELPER, pcChain: ?*u32, prgChain: ?*?*?*CERT_CONTEXT, prgdwErrors: ?*?*u32, prgpbTrustInfo: ?*?*CRYPTOAPI_BLOB, }; pub const CTL_MODIFY_REQUEST = extern struct { pccert: ?*const CERT_CONTEXT, dwOperation: CTL_MODIFY_REQUEST_OPERATION, dwError: u32, }; pub const PFNCFILTERPROC = fn( pCertContext: ?*const CERT_CONTEXT, pfInitialSelectedCert: ?*BOOL, pvCallbackData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const CERT_SELECTUI_INPUT = extern struct { hStore: ?*anyopaque, prgpChain: ?*?*CERT_CHAIN_CONTEXT, cChain: u32, }; pub const CRYPTUI_CERT_MGR_STRUCT = extern struct { dwSize: u32, hwndParent: ?HWND, dwFlags: u32, pwszTitle: ?[*:0]const u16, pszInitUsageOID: ?[*:0]const u8, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_BLOB_INFO = extern struct { dwSize: u32, pGuidSubject: ?*Guid, cbBlob: u32, pbBlob: ?*u8, pwszDisplayName: ?[*:0]const u16, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_STORE_INFO = extern struct { dwSize: u32, cCertStore: u32, rghCertStore: ?*?*anyopaque, pFilterCallback: ?PFNCFILTERPROC, pvCallbackData: ?*anyopaque, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_PVK_FILE_INFO = extern struct { dwSize: u32, pwszPvkFileName: ?PWSTR, pwszProvName: ?PWSTR, dwProvType: u32, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_CERT_PVK_INFO = extern struct { dwSize: u32, pwszSigningCertFileName: ?PWSTR, dwPvkChoice: CRYPTUI_WIZ_DIGITAL_SIGN_PVK_OPTION, Anonymous: extern union { pPvkFileInfo: ?*CRYPTUI_WIZ_DIGITAL_SIGN_PVK_FILE_INFO, pPvkProvInfo: ?*CRYPT_KEY_PROV_INFO, }, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO = extern struct { dwSize: u32, dwAttrFlags: CRYPTUI_WIZ_DIGITAL_SIGN_SIG_TYPE, pwszDescription: ?[*:0]const u16, pwszMoreInfoLocation: ?[*:0]const u16, pszHashAlg: ?[*:0]const u8, pwszSigningCertDisplayString: ?[*:0]const u16, hAdditionalCertStore: ?*anyopaque, psAuthenticated: ?*CRYPT_ATTRIBUTES, psUnauthenticated: ?*CRYPT_ATTRIBUTES, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_INFO = extern struct { dwSize: u32, dwSubjectChoice: CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT, Anonymous1: extern union { pwszFileName: ?[*:0]const u16, pSignBlobInfo: ?*CRYPTUI_WIZ_DIGITAL_SIGN_BLOB_INFO, }, dwSigningCertChoice: CRYPTUI_WIZ_DIGITAL_SIGN, Anonymous2: extern union { pSigningCertContext: ?*const CERT_CONTEXT, pSigningCertStore: ?*CRYPTUI_WIZ_DIGITAL_SIGN_STORE_INFO, pSigningCertPvkInfo: ?*CRYPTUI_WIZ_DIGITAL_SIGN_CERT_PVK_INFO, }, pwszTimestampURL: ?[*:0]const u16, dwAdditionalCertChoice: CRYPTUI_WIZ_DIGITAL_ADDITIONAL_CERT_CHOICE, pSignExtInfo: ?*CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO, }; pub const CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT = extern struct { dwSize: u32, cbBlob: u32, pbBlob: ?*u8, }; pub const CRYPTUI_INITDIALOG_STRUCT = extern struct { lParam: LPARAM, pCertContext: ?*const CERT_CONTEXT, }; pub const CRYPTUI_VIEWCERTIFICATE_STRUCTW = extern struct { dwSize: u32, hwndParent: ?HWND, dwFlags: CRYPTUI_VIEWCERTIFICATE_FLAGS, szTitle: ?[*:0]const u16, pCertContext: ?*const CERT_CONTEXT, rgszPurposes: ?*?PSTR, cPurposes: u32, Anonymous: extern union { pCryptProviderData: ?*const CRYPT_PROVIDER_DATA, hWVTStateData: ?HANDLE, }, fpCryptProviderDataTrustedUsage: BOOL, idxSigner: u32, idxCert: u32, fCounterSigner: BOOL, idxCounterSigner: u32, cStores: u32, rghStores: ?*?*anyopaque, cPropSheetPages: u32, rgPropSheetPages: ?*PROPSHEETPAGEW, nStartPage: u32, }; pub const CRYPTUI_VIEWCERTIFICATE_STRUCTA = extern struct { dwSize: u32, hwndParent: ?HWND, dwFlags: CRYPTUI_VIEWCERTIFICATE_FLAGS, szTitle: ?[*:0]const u8, pCertContext: ?*const CERT_CONTEXT, rgszPurposes: ?*?PSTR, cPurposes: u32, Anonymous: extern union { pCryptProviderData: ?*const CRYPT_PROVIDER_DATA, hWVTStateData: ?HANDLE, }, fpCryptProviderDataTrustedUsage: BOOL, idxSigner: u32, idxCert: u32, fCounterSigner: BOOL, idxCounterSigner: u32, cStores: u32, rghStores: ?*?*anyopaque, cPropSheetPages: u32, rgPropSheetPages: ?*PROPSHEETPAGEA, nStartPage: u32, }; pub const CRYPTUI_WIZ_EXPORT_INFO = extern struct { dwSize: u32, pwszExportFileName: ?[*:0]const u16, dwSubjectChoice: CRYPTUI_WIZ_EXPORT_SUBJECT, Anonymous: extern union { pCertContext: ?*const CERT_CONTEXT, pCTLContext: ?*CTL_CONTEXT, pCRLContext: ?*CRL_CONTEXT, hCertStore: ?*anyopaque, }, cStores: u32, rghStores: ?*?*anyopaque, }; pub const CRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO = extern struct { dwSize: u32, dwExportFormat: CRYPTUI_WIZ_EXPORT_FORMAT, fExportChain: BOOL, fExportPrivateKeys: BOOL, pwszPassword: ?[*:0]const u16, fStrongEncryption: BOOL, }; pub const CRYPTUI_WIZ_IMPORT_SRC_INFO = extern struct { dwSize: u32, dwSubjectChoice: CRYPTUI_WIZ_IMPORT_SUBJECT_OPTION, Anonymous: extern union { pwszFileName: ?[*:0]const u16, pCertContext: ?*const CERT_CONTEXT, pCTLContext: ?*CTL_CONTEXT, pCRLContext: ?*CRL_CONTEXT, hCertStore: ?*anyopaque, }, dwFlags: CRYPT_KEY_FLAGS, pwszPassword: ?[*:0]const u16, }; //-------------------------------------------------------------------------------- // Section: Functions (10) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIDlgViewContext( dwContextType: u32, pvContext: ?*const anyopaque, hwnd: ?HWND, pwszTitle: ?[*:0]const u16, dwFlags: u32, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIDlgSelectCertificateFromStore( hCertStore: ?*anyopaque, hwnd: ?HWND, pwszTitle: ?[*:0]const u16, pwszDisplayString: ?[*:0]const u16, dwDontUseColumn: u32, dwFlags: u32, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*CERT_CONTEXT; // TODO: this type is limited to platform 'windows6.1' pub extern "CRYPTUI" fn CertSelectionGetSerializedBlob( pcsi: ?*CERT_SELECTUI_INPUT, ppOutBuffer: ?*?*anyopaque, pulOutBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIDlgCertMgr( pCryptUICertMgr: ?*CRYPTUI_CERT_MGR_STRUCT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIWizDigitalSign( dwFlags: u32, hwndParent: ?HWND, pwszWizardTitle: ?[*:0]const u16, pDigitalSignInfo: ?*CRYPTUI_WIZ_DIGITAL_SIGN_INFO, ppSignContext: ?*?*CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIWizFreeDigitalSignContext( pSignContext: ?*CRYPTUI_WIZ_DIGITAL_SIGN_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIDlgViewCertificateW( pCertViewInfo: ?*CRYPTUI_VIEWCERTIFICATE_STRUCTW, pfPropertiesChanged: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIDlgViewCertificateA( pCertViewInfo: ?*CRYPTUI_VIEWCERTIFICATE_STRUCTA, pfPropertiesChanged: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIWizExport( dwFlags: CRYPTUI_WIZ_FLAGS, hwndParent: ?HWND, pwszWizardTitle: ?[*:0]const u16, pExportInfo: ?*CRYPTUI_WIZ_EXPORT_INFO, pvoid: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "CRYPTUI" fn CryptUIWizImport( dwFlags: CRYPTUI_WIZ_FLAGS, hwndParent: ?HWND, pwszWizardTitle: ?[*:0]const u16, pImportSrc: ?*CRYPTUI_WIZ_IMPORT_SRC_INFO, hDestCertStore: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (4) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { pub const CERT_SELECT_STRUCT_ = thismodule.CERT_SELECT_STRUCT_A; pub const CERT_VIEWPROPERTIES_STRUCT_ = thismodule.CERT_VIEWPROPERTIES_STRUCT_A; pub const CRYPTUI_VIEWCERTIFICATE_STRUCT = thismodule.CRYPTUI_VIEWCERTIFICATE_STRUCTA; pub const CryptUIDlgViewCertificate = thismodule.CryptUIDlgViewCertificateA; }, .wide => struct { pub const CERT_SELECT_STRUCT_ = thismodule.CERT_SELECT_STRUCT_W; pub const CERT_VIEWPROPERTIES_STRUCT_ = thismodule.CERT_VIEWPROPERTIES_STRUCT_W; pub const CRYPTUI_VIEWCERTIFICATE_STRUCT = thismodule.CRYPTUI_VIEWCERTIFICATE_STRUCTW; pub const CryptUIDlgViewCertificate = thismodule.CryptUIDlgViewCertificateW; }, .unspecified => if (@import("builtin").is_test) struct { pub const CERT_SELECT_STRUCT_ = *opaque{}; pub const CERT_VIEWPROPERTIES_STRUCT_ = *opaque{}; pub const CRYPTUI_VIEWCERTIFICATE_STRUCT = *opaque{}; pub const CryptUIDlgViewCertificate = *opaque{}; } else struct { pub const CERT_SELECT_STRUCT_ = @compileError("'CERT_SELECT_STRUCT_' requires that UNICODE be set to true or false in the root module"); pub const CERT_VIEWPROPERTIES_STRUCT_ = @compileError("'CERT_VIEWPROPERTIES_STRUCT_' requires that UNICODE be set to true or false in the root module"); pub const CRYPTUI_VIEWCERTIFICATE_STRUCT = @compileError("'CRYPTUI_VIEWCERTIFICATE_STRUCT' requires that UNICODE be set to true or false in the root module"); pub const CryptUIDlgViewCertificate = @compileError("'CryptUIDlgViewCertificate' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (21) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOL = @import("../../foundation.zig").BOOL; const CERT_CHAIN_CONTEXT = @import("../../security/cryptography.zig").CERT_CHAIN_CONTEXT; const CERT_CONTEXT = @import("../../security/cryptography.zig").CERT_CONTEXT; const CRL_CONTEXT = @import("../../security/cryptography.zig").CRL_CONTEXT; const CRYPT_ATTRIBUTES = @import("../../security/cryptography.zig").CRYPT_ATTRIBUTES; const CRYPT_KEY_FLAGS = @import("../../security/cryptography.zig").CRYPT_KEY_FLAGS; const CRYPT_KEY_PROV_INFO = @import("../../security/cryptography.zig").CRYPT_KEY_PROV_INFO; const CRYPT_PROVIDER_DATA = @import("../../security/win_trust.zig").CRYPT_PROVIDER_DATA; const CRYPTOAPI_BLOB = @import("../../security/cryptography.zig").CRYPTOAPI_BLOB; const CTL_CONTEXT = @import("../../security/cryptography.zig").CTL_CONTEXT; const HANDLE = @import("../../foundation.zig").HANDLE; const HINSTANCE = @import("../../foundation.zig").HINSTANCE; const HRESULT = @import("../../foundation.zig").HRESULT; const HWND = @import("../../foundation.zig").HWND; const LPARAM = @import("../../foundation.zig").LPARAM; const PROPSHEETPAGEA = @import("../../ui/controls.zig").PROPSHEETPAGEA; const PROPSHEETPAGEW = @import("../../ui/controls.zig").PROPSHEETPAGEW; const PSTR = @import("../../foundation.zig").PSTR; const PWSTR = @import("../../foundation.zig").PWSTR; const WPARAM = @import("../../foundation.zig").WPARAM; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNCMFILTERPROC")) { _ = PFNCMFILTERPROC; } if (@hasDecl(@This(), "PFNCMHOOKPROC")) { _ = PFNCMHOOKPROC; } if (@hasDecl(@This(), "PFNTRUSTHELPER")) { _ = PFNTRUSTHELPER; } if (@hasDecl(@This(), "PFNCFILTERPROC")) { _ = PFNCFILTERPROC; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/security/cryptography/ui.zig
const std = @import("std"); const registry = @import("registry.zig"); const xml = @import("../xml.zig"); const cparse = @import("c_parse.zig"); const mem = std.mem; const Allocator = mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const api_constants_name = "API Constants"; pub const ParseResult = struct { arena: ArenaAllocator, registry: registry.Registry, pub fn deinit(self: ParseResult) void { self.arena.deinit(); } }; pub fn parseXml(backing_allocator: *Allocator, root: *xml.Element) !ParseResult { var arena = ArenaAllocator.init(backing_allocator); errdefer arena.deinit(); const allocator = &arena.allocator; var reg = registry.Registry{ .copyright = root.getCharData("comment") orelse return error.InvalidRegistry, .decls = try parseDeclarations(allocator, root), .api_constants = try parseApiConstants(allocator, root), .tags = try parseTags(allocator, root), .features = try parseFeatures(allocator, root), .extensions = try parseExtensions(allocator, root), }; return ParseResult{ .arena = arena, .registry = reg, }; } fn parseDeclarations(allocator: *Allocator, root: *xml.Element) ![]registry.Declaration { var types_elem = root.findChildByTag("types") orelse return error.InvalidRegistry; var commands_elem = root.findChildByTag("commands") orelse return error.InvalidRegistry; const decl_upper_bound = types_elem.children.items.len + commands_elem.children.items.len; const decls = try allocator.alloc(registry.Declaration, decl_upper_bound); var count: usize = 0; count += try parseTypes(allocator, decls, types_elem); count += try parseEnums(allocator, decls[count..], root); count += try parseCommands(allocator, decls[count..], commands_elem); return allocator.shrink(decls, count); } fn parseTypes(allocator: *Allocator, out: []registry.Declaration, types_elem: *xml.Element) !usize { var i: usize = 0; var it = types_elem.findChildrenByTag("type"); while (it.next()) |ty| { out[i] = blk: { const category = ty.getAttribute("category") orelse { break :blk try parseForeigntype(ty); }; if (mem.eql(u8, category, "bitmask")) { break :blk try parseBitmaskType(ty); } else if (mem.eql(u8, category, "handle")) { break :blk try parseHandleType(ty); } else if (mem.eql(u8, category, "basetype")) { break :blk try parseBaseType(allocator, ty); } else if (mem.eql(u8, category, "struct")) { break :blk try parseContainer(allocator, ty, false); } else if (mem.eql(u8, category, "union")) { break :blk try parseContainer(allocator, ty, true); } else if (mem.eql(u8, category, "funcpointer")) { break :blk try parseFuncPointer(allocator, ty); } else if (mem.eql(u8, category, "enum")) { break :blk (try parseEnumAlias(ty)) orelse continue; } continue; }; i += 1; } return i; } fn parseForeigntype(ty: *xml.Element) !registry.Declaration { const name = ty.getAttribute("name") orelse return error.InvalidRegistry; const depends = ty.getAttribute("requires") orelse if (mem.eql(u8, name, "int")) "vk_platform" // for some reason, int doesn't depend on vk_platform (but the other c types do) else return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{ .foreign = .{ .depends = depends } }, }; } fn parseBitmaskType(ty: *xml.Element) !registry.Declaration { if (ty.getAttribute("name")) |name| { const alias = ty.getAttribute("alias") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{ .alias = .{ .name = alias, .target = .other_type } }, }; } else { const flags_type = ty.getCharData("type") orelse return error.InvalidRegistry; const bitwidth: u8 = if (mem.eql(u8, flags_type, "VkFlags")) 32 else if (mem.eql(u8, flags_type, "VkFlags64")) 64 else return error.InvalidRegistry; return registry.Declaration{ .name = ty.getCharData("name") orelse return error.InvalidRegistry, .decl_type = .{ .bitmask = .{ // Who knows why these are different fields .bits_enum = ty.getAttribute("requires") orelse ty.getAttribute("bitvalues"), .bitwidth = bitwidth, }, }, }; } } fn parseHandleType(ty: *xml.Element) !registry.Declaration { // Parent is not handled in case of an alias if (ty.getAttribute("name")) |name| { const alias = ty.getAttribute("alias") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{ .alias = .{ .name = alias, .target = .other_type }, }, }; } else { const name = ty.getCharData("name") orelse return error.InvalidRegistry; const handle_type = ty.getCharData("type") orelse return error.InvalidRegistry; const dispatchable = mem.eql(u8, handle_type, "VK_DEFINE_HANDLE"); if (!dispatchable and !mem.eql(u8, handle_type, "VK_DEFINE_NON_DISPATCHABLE_HANDLE")) { return error.InvalidRegistry; } return registry.Declaration{ .name = name, .decl_type = .{ .handle = .{ .parent = ty.getAttribute("parent"), .is_dispatchable = dispatchable, }, }, }; } } fn parseBaseType(allocator: *Allocator, ty: *xml.Element) !registry.Declaration { const name = ty.getCharData("name") orelse return error.InvalidRegistry; if (ty.getCharData("type")) |_| { var tok = cparse.XmlCTokenizer.init(ty); return try cparse.parseTypedef(allocator, &tok); } else { // Either ANativeWindow, AHardwareBuffer or CAMetalLayer. The latter has a lot of // macros, which is why this part is not built into the xml/c parser. return registry.Declaration{ .name = name, .decl_type = .{ .external = {} }, }; } } fn parseContainer(allocator: *Allocator, ty: *xml.Element, is_union: bool) !registry.Declaration { const name = ty.getAttribute("name") orelse return error.InvalidRegistry; if (ty.getAttribute("alias")) |alias| { return registry.Declaration{ .name = name, .decl_type = .{ .alias = .{ .name = alias, .target = .other_type }, }, }; } var members = try allocator.alloc(registry.Container.Field, ty.children.items.len); var i: usize = 0; var it = ty.findChildrenByTag("member"); var maybe_stype: ?[]const u8 = null; while (it.next()) |member| { var xctok = cparse.XmlCTokenizer.init(member); members[i] = try cparse.parseMember(allocator, &xctok); if (mem.eql(u8, members[i].name, "sType")) { if (member.getAttribute("values")) |stype| { maybe_stype = stype; } } i += 1; } members = allocator.shrink(members, i); var maybe_extends: ?[][]const u8 = null; if (ty.getAttribute("structextends")) |extends| { const n_structs = std.mem.count(u8, extends, ",") + 1; maybe_extends = try allocator.alloc([]const u8, n_structs); var struct_extends = std.mem.split(u8, extends, ","); var j: usize = 0; while (struct_extends.next()) |struct_extend| { maybe_extends.?[j] = struct_extend; j += 1; } } it = ty.findChildrenByTag("member"); for (members) |*member| { const member_elem = it.next().?; try parsePointerMeta(.{ .container = members }, &member.field_type, member_elem); } return registry.Declaration{ .name = name, .decl_type = .{ .container = .{ .stype = maybe_stype, .fields = members, .is_union = is_union, .extends = maybe_extends, }, }, }; } fn parseFuncPointer(allocator: *Allocator, ty: *xml.Element) !registry.Declaration { var xctok = cparse.XmlCTokenizer.init(ty); return try cparse.parseTypedef(allocator, &xctok); } // For some reason, the DeclarationType cannot be passed to lenToPointerSize, as // that causes the Zig compiler to generate invalid code for the function. Using a // dedicated enum fixes the issue... const Fields = union(enum) { command: []registry.Command.Param, container: []registry.Container.Field, }; fn lenToPointerSize(fields: Fields, len: []const u8) registry.Pointer.PointerSize { switch (fields) { .command => |params| { for (params) |*param| { if (mem.eql(u8, param.name, len)) { param.is_buffer_len = true; return .{ .other_field = param.name }; } } }, .container => |members| { for (members) |*member| { if (mem.eql(u8, member.name, len)) { member.is_buffer_len = true; return .{ .other_field = member.name }; } } }, } if (mem.eql(u8, len, "null-terminated")) { return .zero_terminated; } else { return .many; } } fn parsePointerMeta(fields: Fields, type_info: *registry.TypeInfo, elem: *xml.Element) !void { if (elem.getAttribute("len")) |lens| { var it = mem.split(u8, lens, ","); var current_type_info = type_info; while (current_type_info.* == .pointer) { // TODO: Check altlen const size = if (it.next()) |len_str| lenToPointerSize(fields, len_str) else .one; current_type_info.pointer.size = size; current_type_info = current_type_info.pointer.child; } if (it.next()) |_| { // There are more elements in the `len` attribute than there are pointers // Something probably went wrong return error.InvalidRegistry; } } if (elem.getAttribute("optional")) |optionals| { var it = mem.split(u8, optionals, ","); var current_type_info = type_info; while (current_type_info.* == .pointer) { if (it.next()) |current_optional| { current_type_info.pointer.is_optional = mem.eql(u8, current_optional, "true"); } else { // There is no information for this pointer, probably incorrect. return error.InvalidRegistry; } current_type_info = current_type_info.pointer.child; } } } fn parseEnumAlias(elem: *xml.Element) !?registry.Declaration { if (elem.getAttribute("alias")) |alias| { const name = elem.getAttribute("name") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{ .alias = .{ .name = alias, .target = .other_type }, }, }; } return null; } fn parseEnums(allocator: *Allocator, out: []registry.Declaration, root: *xml.Element) !usize { var i: usize = 0; var it = root.findChildrenByTag("enums"); while (it.next()) |enums| { const name = enums.getAttribute("name") orelse return error.InvalidRegistry; if (mem.eql(u8, name, api_constants_name)) { continue; } out[i] = .{ .name = name, .decl_type = .{ .enumeration = try parseEnumFields(allocator, enums) }, }; i += 1; } return i; } fn parseEnumFields(allocator: *Allocator, elem: *xml.Element) !registry.Enum { // TODO: `type` was added recently, fall back to checking endswith FlagBits for older versions? const enum_type = elem.getAttribute("type") orelse return error.InvalidRegistry; const is_bitmask = mem.eql(u8, enum_type, "bitmask"); if (!is_bitmask and !mem.eql(u8, enum_type, "enum")) { return error.InvalidRegistry; } const bitwidth = if (elem.getAttribute("bitwidth")) |bitwidth| try std.fmt.parseInt(u8, bitwidth, 10) else 32; const fields = try allocator.alloc(registry.Enum.Field, elem.children.items.len); var i: usize = 0; var it = elem.findChildrenByTag("enum"); while (it.next()) |field| { fields[i] = try parseEnumField(field); i += 1; } return registry.Enum{ .fields = allocator.shrink(fields, i), .bitwidth = bitwidth, .is_bitmask = is_bitmask, }; } fn parseEnumField(field: *xml.Element) !registry.Enum.Field { const is_compat_alias = if (field.getAttribute("comment")) |comment| mem.eql(u8, comment, "Backwards-compatible alias containing a typo") or mem.eql(u8, comment, "Deprecated name for backwards compatibility") else false; const name = field.getAttribute("name") orelse return error.InvalidRegistry; const value: registry.Enum.Value = blk: { // An enum variant's value could be defined by any of the following attributes: // - value: Straight up value of the enum variant, in either base 10 or 16 (prefixed with 0x). // - bitpos: Used for bitmasks, and can also be set in extensions. // - alias: The field is an alias of another variant within the same enum. // - offset: Used with features and extensions, where a non-bitpos value is added to an enum. // The value is given by `1e9 + (extr_nr - 1) * 1e3 + offset`, where `ext_nr` is either // given by the `extnumber` field (in the case of a feature), or given in the parent <extension> // tag. In the latter case its passed via the `ext_nr` parameter. if (field.getAttribute("value")) |value| { if (mem.startsWith(u8, value, "0x")) { break :blk .{ .bit_vector = try std.fmt.parseInt(i32, value[2..], 16) }; } else { break :blk .{ .int = try std.fmt.parseInt(i32, value, 10) }; } } else if (field.getAttribute("bitpos")) |bitpos| { break :blk .{ .bitpos = try std.fmt.parseInt(u6, bitpos, 10) }; } else if (field.getAttribute("alias")) |alias| { break :blk .{ .alias = .{ .name = alias, .is_compat_alias = is_compat_alias } }; } else { return error.InvalidRegistry; } }; return registry.Enum.Field{ .name = name, .value = value, }; } fn parseCommands(allocator: *Allocator, out: []registry.Declaration, commands_elem: *xml.Element) !usize { var i: usize = 0; var it = commands_elem.findChildrenByTag("command"); while (it.next()) |elem| { out[i] = try parseCommand(allocator, elem); i += 1; } return i; } fn splitCommaAlloc(allocator: *Allocator, text: []const u8) ![][]const u8 { var n_codes: usize = 1; for (text) |c| { if (c == ',') n_codes += 1; } const codes = try allocator.alloc([]const u8, n_codes); var it = mem.split(u8, text, ","); for (codes) |*code| { code.* = it.next().?; } return codes; } fn parseCommand(allocator: *Allocator, elem: *xml.Element) !registry.Declaration { if (elem.getAttribute("alias")) |alias| { const name = elem.getAttribute("name") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{ .alias = .{ .name = alias, .target = .other_command }, }, }; } const proto = elem.findChildByTag("proto") orelse return error.InvalidRegistry; var proto_xctok = cparse.XmlCTokenizer.init(proto); const command_decl = try cparse.parseParamOrProto(allocator, &proto_xctok); var params = try allocator.alloc(registry.Command.Param, elem.children.items.len); var i: usize = 0; var it = elem.findChildrenByTag("param"); while (it.next()) |param| { var xctok = cparse.XmlCTokenizer.init(param); const decl = try cparse.parseParamOrProto(allocator, &xctok); params[i] = .{ .name = decl.name, .param_type = decl.decl_type.typedef, .is_buffer_len = false, }; i += 1; } const return_type = try allocator.create(registry.TypeInfo); return_type.* = command_decl.decl_type.typedef; const success_codes = if (elem.getAttribute("successcodes")) |codes| try splitCommaAlloc(allocator, codes) else &[_][]const u8{}; const error_codes = if (elem.getAttribute("errorcodes")) |codes| try splitCommaAlloc(allocator, codes) else &[_][]const u8{}; params = allocator.shrink(params, i); it = elem.findChildrenByTag("param"); for (params) |*param| { const param_elem = it.next().?; try parsePointerMeta(.{ .command = params }, &param.param_type, param_elem); } return registry.Declaration{ .name = command_decl.name, .decl_type = .{ .command = .{ .params = params, .return_type = return_type, .success_codes = success_codes, .error_codes = error_codes, }, }, }; } fn parseApiConstants(allocator: *Allocator, root: *xml.Element) ![]registry.ApiConstant { var enums = blk: { var it = root.findChildrenByTag("enums"); while (it.next()) |child| { const name = child.getAttribute("name") orelse continue; if (mem.eql(u8, name, api_constants_name)) { break :blk child; } } return error.InvalidRegistry; }; var types = root.findChildByTag("types") orelse return error.InvalidRegistry; const n_defines = blk: { var n_defines: usize = 0; var it = types.findChildrenByTag("type"); while (it.next()) |ty| { if (ty.getAttribute("category")) |category| { if (mem.eql(u8, category, "define")) { n_defines += 1; } } } break :blk n_defines; }; const constants = try allocator.alloc(registry.ApiConstant, enums.children.items.len + n_defines); var i: usize = 0; var it = enums.findChildrenByTag("enum"); while (it.next()) |constant| { const expr = if (constant.getAttribute("value")) |expr| expr else if (constant.getAttribute("alias")) |alias| alias else return error.InvalidRegistry; constants[i] = .{ .name = constant.getAttribute("name") orelse return error.InvalidRegistry, .value = .{ .expr = expr }, }; i += 1; } i += try parseDefines(types, constants[i..]); return allocator.shrink(constants, i); } fn parseDefines(types: *xml.Element, out: []registry.ApiConstant) !usize { var i: usize = 0; var it = types.findChildrenByTag("type"); while (it.next()) |ty| { const category = ty.getAttribute("category") orelse continue; if (!mem.eql(u8, category, "define")) { continue; } const name = ty.getCharData("name") orelse continue; if (mem.eql(u8, name, "VK_HEADER_VERSION")) { out[i] = .{ .name = name, .value = .{ .expr = mem.trim(u8, ty.children.items[2].CharData, " ") }, }; } else { var xctok = cparse.XmlCTokenizer.init(ty); out[i] = .{ .name = name, .value = .{ .version = cparse.parseVersion(&xctok) catch continue }, }; } i += 1; } return i; } fn parseTags(allocator: *Allocator, root: *xml.Element) ![]registry.Tag { var tags_elem = root.findChildByTag("tags") orelse return error.InvalidRegistry; const tags = try allocator.alloc(registry.Tag, tags_elem.children.items.len); var i: usize = 0; var it = tags_elem.findChildrenByTag("tag"); while (it.next()) |tag| { tags[i] = .{ .name = tag.getAttribute("name") orelse return error.InvalidRegistry, .author = tag.getAttribute("author") orelse return error.InvalidRegistry, }; i += 1; } return allocator.shrink(tags, i); } fn parseFeatures(allocator: *Allocator, root: *xml.Element) ![]registry.Feature { var it = root.findChildrenByTag("feature"); var count: usize = 0; while (it.next()) |_| count += 1; const features = try allocator.alloc(registry.Feature, count); var i: usize = 0; it = root.findChildrenByTag("feature"); while (it.next()) |feature| { features[i] = try parseFeature(allocator, feature); i += 1; } return features; } fn parseFeature(allocator: *Allocator, feature: *xml.Element) !registry.Feature { const name = feature.getAttribute("name") orelse return error.InvalidRegistry; const feature_level = blk: { const number = feature.getAttribute("number") orelse return error.InvalidRegistry; break :blk try splitFeatureLevel(number, "."); }; var requires = try allocator.alloc(registry.Require, feature.children.items.len); var i: usize = 0; var it = feature.findChildrenByTag("require"); while (it.next()) |require| { requires[i] = try parseRequire(allocator, require, null); i += 1; } return registry.Feature{ .name = name, .level = feature_level, .requires = allocator.shrink(requires, i), }; } fn parseEnumExtension(elem: *xml.Element, parent_extnumber: ?u31) !?registry.Require.EnumExtension { // check for either _SPEC_VERSION or _EXTENSION_NAME const extends = elem.getAttribute("extends") orelse return null; if (elem.getAttribute("offset")) |offset_str| { const offset = try std.fmt.parseInt(u31, offset_str, 10); const name = elem.getAttribute("name") orelse return error.InvalidRegistry; const extnumber = if (elem.getAttribute("extnumber")) |num| try std.fmt.parseInt(u31, num, 10) else null; const actual_extnumber = extnumber orelse parent_extnumber orelse return error.InvalidRegistry; const value = blk: { const abs_value = enumExtOffsetToValue(actual_extnumber, offset); if (elem.getAttribute("dir")) |dir| { if (mem.eql(u8, dir, "-")) { break :blk -@as(i32, abs_value); } else { return error.InvalidRegistry; } } break :blk @as(i32, abs_value); }; return registry.Require.EnumExtension{ .extends = extends, .extnumber = actual_extnumber, .field = .{ .name = name, .value = .{ .int = value }, }, }; } return registry.Require.EnumExtension{ .extends = extends, .extnumber = parent_extnumber, .field = try parseEnumField(elem), }; } fn enumExtOffsetToValue(extnumber: u31, offset: u31) u31 { const extension_value_base = 1000000000; const extension_block = 1000; return extension_value_base + (extnumber - 1) * extension_block + offset; } fn parseRequire(allocator: *Allocator, require: *xml.Element, extnumber: ?u31) !registry.Require { var n_extends: usize = 0; var n_types: usize = 0; var n_commands: usize = 0; var it = require.elements(); while (it.next()) |elem| { if (mem.eql(u8, elem.tag, "enum")) { n_extends += 1; } else if (mem.eql(u8, elem.tag, "type")) { n_types += 1; } else if (mem.eql(u8, elem.tag, "command")) { n_commands += 1; } } const extends = try allocator.alloc(registry.Require.EnumExtension, n_extends); const types = try allocator.alloc([]const u8, n_types); const commands = try allocator.alloc([]const u8, n_commands); var i_extends: usize = 0; var i_types: usize = 0; var i_commands: usize = 0; it = require.elements(); while (it.next()) |elem| { if (mem.eql(u8, elem.tag, "enum")) { if (try parseEnumExtension(elem, extnumber)) |ext| { extends[i_extends] = ext; i_extends += 1; } } else if (mem.eql(u8, elem.tag, "type")) { types[i_types] = elem.getAttribute("name") orelse return error.InvalidRegistry; i_types += 1; } else if (mem.eql(u8, elem.tag, "command")) { commands[i_commands] = elem.getAttribute("name") orelse return error.InvalidRegistry; i_commands += 1; } } const required_feature_level = blk: { const feature_level = require.getAttribute("feature") orelse break :blk null; if (!mem.startsWith(u8, feature_level, "VK_VERSION_")) { return error.InvalidRegistry; } break :blk try splitFeatureLevel(feature_level["VK_VERSION_".len..], "_"); }; return registry.Require{ .extends = allocator.shrink(extends, i_extends), .types = types, .commands = commands, .required_feature_level = required_feature_level, .required_extension = require.getAttribute("extension"), }; } fn parseExtensions(allocator: *Allocator, root: *xml.Element) ![]registry.Extension { const extensions_elem = root.findChildByTag("extensions") orelse return error.InvalidRegistry; const extensions = try allocator.alloc(registry.Extension, extensions_elem.children.items.len); var i: usize = 0; var it = extensions_elem.findChildrenByTag("extension"); while (it.next()) |extension| { // Some extensions (in particular 94) are disabled, so just skip them if (extension.getAttribute("supported")) |supported| { if (mem.eql(u8, supported, "disabled")) { continue; } } extensions[i] = try parseExtension(allocator, extension); i += 1; } return allocator.shrink(extensions, i); } fn findExtVersion(extension: *xml.Element) !u32 { var req_it = extension.findChildrenByTag("require"); while (req_it.next()) |req| { var enum_it = req.findChildrenByTag("enum"); while (enum_it.next()) |e| { const name = e.getAttribute("name") orelse continue; const value = e.getAttribute("value") orelse continue; if (mem.endsWith(u8, name, "_SPEC_VERSION")) { return try std.fmt.parseInt(u32, value, 10); } } } return error.InvalidRegistry; } fn parseExtension(allocator: *Allocator, extension: *xml.Element) !registry.Extension { const name = extension.getAttribute("name") orelse return error.InvalidRegistry; const platform = extension.getAttribute("platform"); const version = try findExtVersion(extension); // For some reason there are two ways for an extension to state its required // feature level: both seperately in each <require> tag, or using // the requiresCore attribute. const requires_core = if (extension.getAttribute("requiresCore")) |feature_level| try splitFeatureLevel(feature_level, ".") else null; const promoted_to: registry.Extension.Promotion = blk: { const promotedto = extension.getAttribute("promotedto") orelse break :blk .none; if (mem.startsWith(u8, promotedto, "VK_VERSION_")) { const feature_level = try splitFeatureLevel(promotedto["VK_VERSION_".len..], "_"); break :blk .{ .feature = feature_level }; } break :blk .{ .extension = promotedto }; }; const number = blk: { const number_str = extension.getAttribute("number") orelse return error.InvalidRegistry; break :blk try std.fmt.parseInt(u31, number_str, 10); }; const ext_type: ?registry.Extension.ExtensionType = blk: { const ext_type_str = extension.getAttribute("type") orelse break :blk null; if (mem.eql(u8, ext_type_str, "instance")) { break :blk .instance; } else if (mem.eql(u8, ext_type_str, "device")) { break :blk .device; } else { return error.InvalidRegistry; } }; const depends = blk: { const requires_str = extension.getAttribute("requires") orelse break :blk &[_][]const u8{}; break :blk try splitCommaAlloc(allocator, requires_str); }; var requires = try allocator.alloc(registry.Require, extension.children.items.len); var i: usize = 0; var it = extension.findChildrenByTag("require"); while (it.next()) |require| { requires[i] = try parseRequire(allocator, require, number); i += 1; } return registry.Extension{ .name = name, .number = number, .version = version, .extension_type = ext_type, .depends = depends, .promoted_to = promoted_to, .platform = platform, .required_feature_level = requires_core, .requires = allocator.shrink(requires, i), }; } fn splitFeatureLevel(ver: []const u8, split: []const u8) !registry.FeatureLevel { var it = mem.split(u8, ver, split); const major = it.next() orelse return error.InvalidFeatureLevel; const minor = it.next() orelse return error.InvalidFeatureLevel; if (it.next() != null) { return error.InvalidFeatureLevel; } return registry.FeatureLevel{ .major = try std.fmt.parseInt(u32, major, 10), .minor = try std.fmt.parseInt(u32, minor, 10), }; }
generator/vulkan/parse.zig
const std = @import("std"); const assert = std.debug.assert; const math = std.math; const L = std.unicode.utf8ToUtf16LeStringLiteral; const zwin32 = @import("zwin32"); const w = zwin32.base; const d3d12 = zwin32.d3d12; const dml = zwin32.directml; const hrPanic = zwin32.hrPanic; const hrPanicOnFail = zwin32.hrPanicOnFail; const zd3d12 = @import("zd3d12"); const common = @import("common"); const c = common.c; const vm = common.vectormath; const GuiRenderer = common.GuiRenderer; const Vec3 = vm.Vec3; const Vec4 = vm.Vec4; const Mat4 = vm.Mat4; pub export const D3D12SDKVersion: u32 = 4; pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\"; const content_dir = @import("build_options").content_dir; const window_name = "zig-gamedev: mesh shader test"; const window_width = 1920; const window_height = 1080; // Also need to change MAX_NUM_VERTICES and MAX_NUM_TRIANGLES in mesh_shader_test.hlsl const max_num_meshlet_vertices: usize = 64; const max_num_meshlet_triangles: usize = 64; const mesh_engine = 1; const Vertex = struct { position: [3]f32, normal: [3]f32, }; const Mesh = struct { index_offset: u32, vertex_offset: u32, meshlet_offset: u32, num_indices: u32, num_vertices: u32, num_meshlets: u32, }; const Meshlet = struct { data_offset: u32 align(8), num_vertices: u16, num_triangles: u16, }; comptime { assert(@sizeOf(Meshlet) == 8); assert(@alignOf(Meshlet) == 8); } const Pso_DrawConst = extern struct { object_to_clip: Mat4, }; const DrawMode = enum { mesh_shader, vertex_shader, vertex_shader_fixed, }; const DemoState = struct { grfx: zd3d12.GraphicsContext, gui: GuiRenderer, frame_stats: common.FrameStats, mesh_shader_pso: zd3d12.PipelineHandle, vertex_shader_pso: zd3d12.PipelineHandle, vertex_shader_fixed_pso: zd3d12.PipelineHandle, vertex_buffer: zd3d12.ResourceHandle, vertex_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE, index_buffer: zd3d12.ResourceHandle, index_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE, meshlet_buffer: zd3d12.ResourceHandle, meshlet_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE, meshlet_data_buffer: zd3d12.ResourceHandle, meshlet_data_buffer_srv: d3d12.CPU_DESCRIPTOR_HANDLE, depth_texture: zd3d12.ResourceHandle, depth_texture_dsv: d3d12.CPU_DESCRIPTOR_HANDLE, meshes: std.ArrayList(Mesh), draw_mode: DrawMode, num_objects_to_draw: i32, camera: struct { position: Vec3, forward: Vec3, pitch: f32, yaw: f32, }, mouse: struct { cursor_prev_x: i32, cursor_prev_y: i32, }, }; fn loadMeshAndGenerateMeshlets( arena_allocator: std.mem.Allocator, file_path: []const u8, all_meshes: *std.ArrayList(Mesh), all_vertices: *std.ArrayList(Vertex), all_indices: *std.ArrayList(u32), all_meshlets: *std.ArrayList(Meshlet), all_meshlets_data: *std.ArrayList(u32), ) void { var src_positions = std.ArrayList([3]f32).init(arena_allocator); var src_normals = std.ArrayList([3]f32).init(arena_allocator); var src_indices = std.ArrayList(u32).init(arena_allocator); const data = common.parseAndLoadGltfFile(file_path); defer c.cgltf_free(data); common.appendMeshPrimitive(data, 0, 0, &src_indices, &src_positions, &src_normals, null, null); var src_vertices = std.ArrayList(Vertex).initCapacity( arena_allocator, src_positions.items.len, ) catch unreachable; for (src_positions.items) |_, index| { src_vertices.appendAssumeCapacity(.{ .position = src_positions.items[index], .normal = src_normals.items[index], }); } var remap = std.ArrayList(u32).init(arena_allocator); remap.resize(src_indices.items.len) catch unreachable; const num_unique_vertices = c.meshopt_generateVertexRemap( remap.items.ptr, src_indices.items.ptr, src_indices.items.len, src_vertices.items.ptr, src_vertices.items.len, @sizeOf(Vertex), ); var opt_vertices = std.ArrayList(Vertex).init(arena_allocator); opt_vertices.resize(num_unique_vertices) catch unreachable; c.meshopt_remapVertexBuffer( opt_vertices.items.ptr, src_vertices.items.ptr, src_vertices.items.len, @sizeOf(Vertex), remap.items.ptr, ); var opt_indices = std.ArrayList(u32).init(arena_allocator); opt_indices.resize(src_indices.items.len) catch unreachable; c.meshopt_remapIndexBuffer( opt_indices.items.ptr, src_indices.items.ptr, src_indices.items.len, remap.items.ptr, ); c.meshopt_optimizeVertexCache( opt_indices.items.ptr, opt_indices.items.ptr, opt_indices.items.len, opt_vertices.items.len, ); const num_opt_vertices = c.meshopt_optimizeVertexFetch( opt_vertices.items.ptr, opt_indices.items.ptr, opt_indices.items.len, opt_vertices.items.ptr, opt_vertices.items.len, @sizeOf(Vertex), ); assert(num_opt_vertices == opt_vertices.items.len); const max_num_meshlets = c.meshopt_buildMeshletsBound( opt_indices.items.len, max_num_meshlet_vertices, max_num_meshlet_triangles, ); var meshlets = std.ArrayList(c.meshopt_Meshlet).init(arena_allocator); var meshlet_vertices = std.ArrayList(u32).init(arena_allocator); var meshlet_triangles = std.ArrayList(u8).init(arena_allocator); meshlets.resize(max_num_meshlets) catch unreachable; meshlet_vertices.resize(max_num_meshlets * max_num_meshlet_vertices) catch unreachable; meshlet_triangles.resize(max_num_meshlets * max_num_meshlet_triangles * 3) catch unreachable; const num_meshlets = c.meshopt_buildMeshlets( meshlets.items.ptr, meshlet_vertices.items.ptr, meshlet_triangles.items.ptr, opt_indices.items.ptr, opt_indices.items.len, @ptrCast([*c]const f32, opt_vertices.items.ptr), opt_vertices.items.len, @sizeOf(Vertex), max_num_meshlet_vertices, max_num_meshlet_triangles, 0.0, ); assert(num_meshlets <= max_num_meshlets); meshlets.resize(num_meshlets) catch unreachable; all_meshes.append(.{ .index_offset = @intCast(u32, all_indices.items.len), .vertex_offset = @intCast(u32, all_vertices.items.len), .meshlet_offset = @intCast(u32, all_meshlets.items.len), .num_indices = @intCast(u32, opt_indices.items.len), .num_vertices = @intCast(u32, opt_vertices.items.len), .num_meshlets = @intCast(u32, meshlets.items.len), }) catch unreachable; for (meshlets.items) |src_meshlet| { const meshlet = Meshlet{ .data_offset = @intCast(u32, all_meshlets_data.items.len), .num_vertices = @intCast(u16, src_meshlet.vertex_count), .num_triangles = @intCast(u16, src_meshlet.triangle_count), }; all_meshlets.append(meshlet) catch unreachable; var i: u32 = 0; while (i < src_meshlet.vertex_count) : (i += 1) { all_meshlets_data.append(meshlet_vertices.items[src_meshlet.vertex_offset + i]) catch unreachable; } i = 0; while (i < src_meshlet.triangle_count) : (i += 1) { const index0 = @intCast(u10, meshlet_triangles.items[src_meshlet.triangle_offset + i * 3 + 0]); const index1 = @intCast(u10, meshlet_triangles.items[src_meshlet.triangle_offset + i * 3 + 1]); const index2 = @intCast(u10, meshlet_triangles.items[src_meshlet.triangle_offset + i * 3 + 2]); const prim = @intCast(u32, index0) | (@intCast(u32, index1) << 10) | (@intCast(u32, index2) << 20); all_meshlets_data.append(prim) catch unreachable; } } all_indices.appendSlice(opt_indices.items) catch unreachable; all_vertices.appendSlice(opt_vertices.items) catch unreachable; } fn init(gpa_allocator: std.mem.Allocator) DemoState { const window = common.initWindow(gpa_allocator, window_name, window_width, window_height) catch unreachable; var arena_allocator_state = std.heap.ArenaAllocator.init(gpa_allocator); defer arena_allocator_state.deinit(); const arena_allocator = arena_allocator_state.allocator(); var grfx = zd3d12.GraphicsContext.init(gpa_allocator, window); // Check for Mesh Shader support. { var options7: d3d12.FEATURE_DATA_D3D12_OPTIONS7 = undefined; const res = grfx.device.CheckFeatureSupport( .OPTIONS7, &options7, @sizeOf(d3d12.FEATURE_DATA_D3D12_OPTIONS7), ); if (options7.MeshShaderTier == .NOT_SUPPORTED or res != w.S_OK) { _ = w.user32.messageBoxA( window, "This applications requires graphics card that supports Mesh Shader " ++ "(NVIDIA GeForce Turing or newer, AMD Radeon RX 6000 or newer).", "No DirectX 12 Mesh Shader support", w.user32.MB_OK | w.user32.MB_ICONERROR, ) catch 0; w.kernel32.ExitProcess(0); } } const mesh_shader_pso = blk: { var pso_desc = d3d12.MESH_SHADER_PIPELINE_STATE_DESC.initDefault(); pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.DSVFormat = .D32_FLOAT; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; pso_desc.SampleDesc = .{ .Count = 1, .Quality = 0 }; break :blk grfx.createMeshShaderPipeline( arena_allocator, &pso_desc, null, content_dir ++ "shaders/mesh_shader.ms.cso", content_dir ++ "shaders/mesh_shader.ps.cso", ); }; const vertex_shader_pso = blk: { var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.DSVFormat = .D32_FLOAT; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; pso_desc.SampleDesc = .{ .Count = 1, .Quality = 0 }; break :blk grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/vertex_shader.vs.cso", content_dir ++ "shaders/vertex_shader.ps.cso", ); }; const vertex_shader_fixed_pso = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("Position", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; pso_desc.DSVFormat = .D32_FLOAT; pso_desc.SampleDesc = .{ .Count = 1, .Quality = 0 }; break :blk grfx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/vertex_shader_fixed.vs.cso", content_dir ++ "shaders/vertex_shader_fixed.ps.cso", ); }; var all_meshes = std.ArrayList(Mesh).init(gpa_allocator); var all_vertices = std.ArrayList(Vertex).init(arena_allocator); var all_indices = std.ArrayList(u32).init(arena_allocator); var all_meshlets = std.ArrayList(Meshlet).init(arena_allocator); var all_meshlets_data = std.ArrayList(u32).init(arena_allocator); loadMeshAndGenerateMeshlets( arena_allocator, content_dir ++ "cube.gltf", &all_meshes, &all_vertices, &all_indices, &all_meshlets, &all_meshlets_data, ); loadMeshAndGenerateMeshlets( arena_allocator, content_dir ++ "engine.gltf", &all_meshes, &all_vertices, &all_indices, &all_meshlets, &all_meshlets_data, ); const vertex_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(all_vertices.items.len * @sizeOf(Vertex)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const vertex_buffer_srv = blk: { const srv = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1); grfx.device.CreateShaderResourceView( grfx.lookupResource(vertex_buffer).?, &d3d12.SHADER_RESOURCE_VIEW_DESC.initStructuredBuffer( 0, @intCast(u32, all_vertices.items.len), @sizeOf(Vertex), ), srv, ); break :blk srv; }; const index_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(all_indices.items.len * @sizeOf(u32)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const index_buffer_srv = blk: { const srv = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1); grfx.device.CreateShaderResourceView( grfx.lookupResource(index_buffer).?, &d3d12.SHADER_RESOURCE_VIEW_DESC.initTypedBuffer(.R32_UINT, 0, @intCast(u32, all_indices.items.len)), srv, ); break :blk srv; }; const meshlet_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(all_meshlets.items.len * @sizeOf(Meshlet)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const meshlet_buffer_srv = blk: { const srv = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1); grfx.device.CreateShaderResourceView( grfx.lookupResource(meshlet_buffer).?, &d3d12.SHADER_RESOURCE_VIEW_DESC.initStructuredBuffer( 0, @intCast(u32, all_meshlets.items.len), @sizeOf(Meshlet), ), srv, ); break :blk srv; }; const meshlet_data_buffer = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(all_meshlets_data.items.len * @sizeOf(u32)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); const meshlet_data_buffer_srv = blk: { const srv = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1); grfx.device.CreateShaderResourceView( grfx.lookupResource(meshlet_data_buffer).?, &d3d12.SHADER_RESOURCE_VIEW_DESC.initTypedBuffer( .R32_UINT, 0, @intCast(u32, all_meshlets_data.items.len), ), srv, ); break :blk srv; }; const depth_texture = grfx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d(.D32_FLOAT, grfx.viewport_width, grfx.viewport_height, 1); desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | d3d12.RESOURCE_FLAG_DENY_SHADER_RESOURCE; break :blk desc; }, d3d12.RESOURCE_STATE_DEPTH_WRITE, &d3d12.CLEAR_VALUE.initDepthStencil(.D32_FLOAT, 1.0, 0), ) catch |err| hrPanic(err); const depth_texture_dsv = blk: { const dsv = grfx.allocateCpuDescriptors(.DSV, 1); grfx.device.CreateDepthStencilView(grfx.lookupResource(depth_texture).?, null, dsv); break :blk dsv; }; // // Begin data upload to the GPU. // grfx.beginFrame(); var gui = GuiRenderer.init(arena_allocator, &grfx, 1, content_dir); // Upload vertex buffer. { const upload = grfx.allocateUploadBufferRegion(Vertex, @intCast(u32, all_vertices.items.len)); for (all_vertices.items) |vertex, i| upload.cpu_slice[i] = vertex; grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(vertex_buffer).?, 0, upload.buffer, upload.buffer_offset, upload.cpu_slice.len * @sizeOf(@TypeOf(upload.cpu_slice[0])), ); grfx.addTransitionBarrier(vertex_buffer, d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); } // Upload index buffer. { const upload = grfx.allocateUploadBufferRegion(u32, @intCast(u32, all_indices.items.len)); for (all_indices.items) |index, i| upload.cpu_slice[i] = index; grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(index_buffer).?, 0, upload.buffer, upload.buffer_offset, upload.cpu_slice.len * @sizeOf(@TypeOf(upload.cpu_slice[0])), ); grfx.addTransitionBarrier(index_buffer, d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); } // Upload meshlet buffer. { const upload = grfx.allocateUploadBufferRegion(Meshlet, @intCast(u32, all_meshlets.items.len)); for (all_meshlets.items) |meshlet, i| upload.cpu_slice[i] = meshlet; grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(meshlet_buffer).?, 0, upload.buffer, upload.buffer_offset, upload.cpu_slice.len * @sizeOf(@TypeOf(upload.cpu_slice[0])), ); grfx.addTransitionBarrier(meshlet_buffer, d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); } // Upload meshlet data buffer. { const upload = grfx.allocateUploadBufferRegion(u32, @intCast(u32, all_meshlets_data.items.len)); for (all_meshlets_data.items) |meshlet_data, i| upload.cpu_slice[i] = meshlet_data; grfx.cmdlist.CopyBufferRegion( grfx.lookupResource(meshlet_data_buffer).?, 0, upload.buffer, upload.buffer_offset, upload.cpu_slice.len * @sizeOf(@TypeOf(upload.cpu_slice[0])), ); grfx.addTransitionBarrier(meshlet_data_buffer, d3d12.RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); grfx.flushResourceBarriers(); } grfx.endFrame(); grfx.finishGpuCommands(); return .{ .grfx = grfx, .gui = gui, .frame_stats = common.FrameStats.init(), .mesh_shader_pso = mesh_shader_pso, .vertex_shader_pso = vertex_shader_pso, .vertex_shader_fixed_pso = vertex_shader_fixed_pso, .vertex_buffer = vertex_buffer, .vertex_buffer_srv = vertex_buffer_srv, .depth_texture = depth_texture, .depth_texture_dsv = depth_texture_dsv, .index_buffer = index_buffer, .index_buffer_srv = index_buffer_srv, .meshlet_buffer = meshlet_buffer, .meshlet_buffer_srv = meshlet_buffer_srv, .meshlet_data_buffer = meshlet_data_buffer, .meshlet_data_buffer_srv = meshlet_data_buffer_srv, .meshes = all_meshes, .draw_mode = .mesh_shader, .num_objects_to_draw = 16, .camera = .{ .position = Vec3.init(0.0, 0.0, -2.0), .forward = Vec3.init(0.0, 0.0, 1.0), .pitch = 0.0, .yaw = 0.0, }, .mouse = .{ .cursor_prev_x = 0, .cursor_prev_y = 0, }, }; } fn deinit(demo: *DemoState, gpa_allocator: std.mem.Allocator) void { demo.grfx.finishGpuCommands(); demo.meshes.deinit(); demo.gui.deinit(&demo.grfx); demo.grfx.deinit(gpa_allocator); common.deinitWindow(gpa_allocator); demo.* = undefined; } fn update(demo: *DemoState) void { demo.frame_stats.update(demo.grfx.window, window_name); const dt = demo.frame_stats.delta_time; common.newImGuiFrame(dt); c.igSetNextWindowPos( c.ImVec2{ .x = @intToFloat(f32, demo.grfx.viewport_width) - 600.0 - 20, .y = 20.0 }, c.ImGuiCond_FirstUseEver, c.ImVec2{ .x = 0.0, .y = 0.0 }, ); c.igSetNextWindowSize(.{ .x = 600.0, .y = -1 }, c.ImGuiCond_Always); _ = c.igBegin( "Demo Settings", null, c.ImGuiWindowFlags_NoMove | c.ImGuiWindowFlags_NoResize | c.ImGuiWindowFlags_NoSavedSettings, ); c.igBulletText("", ""); c.igSameLine(0, -1); c.igTextColored(.{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "Right Mouse Button + drag", ""); c.igSameLine(0, -1); c.igText(" : rotate camera", ""); c.igBulletText("", ""); c.igSameLine(0, -1); c.igTextColored(.{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "W, A, S, D", ""); c.igSameLine(0, -1); c.igText(" : move camera", ""); c.igSpacing(); c.igSpacing(); c.igText("Draw mode:", ""); var draw_mode: i32 = @enumToInt(demo.draw_mode); _ = c.igRadioButton_IntPtr("Mesh Shader emulating VS (no culling)", &draw_mode, 0); _ = c.igRadioButton_IntPtr("VS with manual vertex fetching (no HW index buffer)", &draw_mode, 1); _ = c.igRadioButton_IntPtr("VS with fixed function vertex fetching", &draw_mode, 2); demo.draw_mode = @intToEnum(DrawMode, draw_mode); _ = c.igSliderInt("Num. objects", &demo.num_objects_to_draw, 1, 1000, null, c.ImGuiSliderFlags_None); c.igSpacing(); c.igSpacing(); c.igSpacing(); c.igText("Triangles: "); c.igSameLine(0, -1); c.igTextColored( .{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "%.3f M", @intToFloat(f64, demo.num_objects_to_draw) * @intToFloat(f64, demo.meshes.items[mesh_engine].num_indices / 3) / 1_000_000.0, ); c.igText("Vertices: "); c.igSameLine(0, -1); c.igTextColored( .{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "%.3f M", @intToFloat(f64, demo.num_objects_to_draw) * @intToFloat(f64, demo.meshes.items[mesh_engine].num_vertices) / 1_000_000.0, ); if (demo.draw_mode == .mesh_shader) { c.igText("Meshlets: "); c.igSameLine(0, -1); c.igTextColored( .{ .x = 0, .y = 0.8, .z = 0, .w = 1 }, "%.3f K", @intToFloat(f64, demo.num_objects_to_draw) * @intToFloat(f64, demo.meshes.items[mesh_engine].num_meshlets) / 1_000.0, ); c.igSpacing(); c.igSpacing(); c.igText("Max. vertices / meshlet: %d", max_num_meshlet_vertices); c.igText("Max. triangles / meshlet: %d", max_num_meshlet_triangles); } c.igEnd(); // Handle camera rotation with mouse. { var pos: w.POINT = undefined; _ = w.GetCursorPos(&pos); const delta_x = @intToFloat(f32, pos.x) - @intToFloat(f32, demo.mouse.cursor_prev_x); const delta_y = @intToFloat(f32, pos.y) - @intToFloat(f32, demo.mouse.cursor_prev_y); demo.mouse.cursor_prev_x = pos.x; demo.mouse.cursor_prev_y = pos.y; if (w.GetAsyncKeyState(w.VK_RBUTTON) < 0) { demo.camera.pitch += 0.0025 * delta_y; demo.camera.yaw += 0.0025 * delta_x; demo.camera.pitch = math.min(demo.camera.pitch, 0.48 * math.pi); demo.camera.pitch = math.max(demo.camera.pitch, -0.48 * math.pi); demo.camera.yaw = vm.modAngle(demo.camera.yaw); } } // Handle camera movement with 'WASD' keys. { const speed: f32 = 0.25; const delta_time = demo.frame_stats.delta_time; const transform = Mat4.initRotationX(demo.camera.pitch).mul(Mat4.initRotationY(demo.camera.yaw)); var forward = Vec3.init(0.0, 0.0, 1.0).transform(transform).normalize(); demo.camera.forward = forward; const right = Vec3.init(0.0, 1.0, 0.0).cross(forward).normalize().scale(speed * delta_time); forward = forward.scale(speed * delta_time); if (w.GetAsyncKeyState('W') < 0) { demo.camera.position = demo.camera.position.add(forward); } else if (w.GetAsyncKeyState('S') < 0) { demo.camera.position = demo.camera.position.sub(forward); } if (w.GetAsyncKeyState('D') < 0) { demo.camera.position = demo.camera.position.add(right); } else if (w.GetAsyncKeyState('A') < 0) { demo.camera.position = demo.camera.position.sub(right); } } } fn draw(demo: *DemoState) void { var grfx = &demo.grfx; grfx.beginFrame(); const cam_world_to_view = Mat4.initLookToLh( demo.camera.position, demo.camera.forward, Vec3.init(0.0, 1.0, 0.0), ); const cam_view_to_clip = Mat4.initPerspectiveFovLh( math.pi / 3.0, @intToFloat(f32, grfx.viewport_width) / @intToFloat(f32, grfx.viewport_height), 0.01, 200.0, ); const cam_world_to_clip = cam_world_to_view.mul(cam_view_to_clip); const back_buffer = grfx.getBackBuffer(); grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET); grfx.flushResourceBarriers(); grfx.cmdlist.OMSetRenderTargets( 1, &[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle}, w.TRUE, &demo.depth_texture_dsv, ); grfx.cmdlist.ClearDepthStencilView(demo.depth_texture_dsv, d3d12.CLEAR_FLAG_DEPTH, 1.0, 0, 0, null); grfx.cmdlist.ClearRenderTargetView( back_buffer.descriptor_handle, &[4]f32{ 0.1, 0.2, 0.4, 1.0 }, 0, null, ); // // Draw all objects. // grfx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST); switch (demo.draw_mode) { .mesh_shader => { grfx.setCurrentPipeline(demo.mesh_shader_pso); // Bind global buffers that contain data for *all meshes* and *all meshlets*. grfx.cmdlist.SetGraphicsRootDescriptorTable(2, blk: { const table = grfx.copyDescriptorsToGpuHeap(1, demo.vertex_buffer_srv); _ = grfx.copyDescriptorsToGpuHeap(1, demo.index_buffer_srv); _ = grfx.copyDescriptorsToGpuHeap(1, demo.meshlet_buffer_srv); _ = grfx.copyDescriptorsToGpuHeap(1, demo.meshlet_data_buffer_srv); break :blk table; }); }, .vertex_shader => { grfx.setCurrentPipeline(demo.vertex_shader_pso); // Bind global buffers that contain data for *all meshes*. grfx.cmdlist.SetGraphicsRootDescriptorTable(2, blk: { const table = grfx.copyDescriptorsToGpuHeap(1, demo.vertex_buffer_srv); _ = grfx.copyDescriptorsToGpuHeap(1, demo.index_buffer_srv); break :blk table; }); }, .vertex_shader_fixed => { grfx.setCurrentPipeline(demo.vertex_shader_fixed_pso); grfx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{ .BufferLocation = grfx.lookupResource(demo.vertex_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, grfx.getResourceSize(demo.vertex_buffer)), .StrideInBytes = @sizeOf(Vertex), }}); grfx.cmdlist.IASetIndexBuffer(&.{ .BufferLocation = grfx.lookupResource(demo.index_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = @intCast(u32, grfx.getResourceSize(demo.index_buffer)), .Format = .R32_UINT, }); }, } var entity_index: i32 = 0; while (entity_index < demo.num_objects_to_draw) : (entity_index += 1) { // Upload per-draw constant data. { const position = Vec3.init(0.0, 0.0, @intToFloat(f32, entity_index) * 2.5); const mem = grfx.allocateUploadMemory(Pso_DrawConst, 1); mem.cpu_slice[0] = .{ .object_to_clip = Mat4.initTranslation(position).mul(cam_world_to_clip).transpose(), }; grfx.cmdlist.SetGraphicsRootConstantBufferView(0, mem.gpu_base); } const mesh = &demo.meshes.items[mesh_engine]; switch (demo.draw_mode) { .mesh_shader => { // Select a mesh to draw by specifying offsets in global buffers. grfx.cmdlist.SetGraphicsRoot32BitConstants(1, 2, &[_]u32{ mesh.vertex_offset, mesh.meshlet_offset, }, 0); grfx.cmdlist.DispatchMesh(mesh.num_meshlets, 1, 1); }, .vertex_shader => { // Select a mesh to draw by specifying offsets in global buffers. grfx.cmdlist.SetGraphicsRoot32BitConstants(1, 2, &[_]u32{ mesh.vertex_offset, mesh.index_offset, }, 0); grfx.cmdlist.DrawInstanced(mesh.num_indices, 1, 0, 0); }, .vertex_shader_fixed => { grfx.cmdlist.DrawIndexedInstanced( mesh.num_indices, 1, mesh.index_offset, @intCast(i32, mesh.vertex_offset), 0, ); }, } } demo.gui.draw(grfx); grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT); grfx.flushResourceBarriers(); grfx.endFrame(); } pub fn main() !void { common.init(); defer common.deinit(); var gpa_allocator_state = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa_allocator_state.deinit(); std.debug.assert(leaked == false); } const gpa_allocator = gpa_allocator_state.allocator(); var demo = init(gpa_allocator); defer deinit(&demo, gpa_allocator); while (true) { var message = std.mem.zeroes(w.user32.MSG); const has_message = w.user32.peekMessageA(&message, null, 0, 0, w.user32.PM_REMOVE) catch false; if (has_message) { _ = w.user32.translateMessage(&message); _ = w.user32.dispatchMessageA(&message); if (message.message == w.user32.WM_QUIT) { break; } } else { update(&demo); draw(&demo); } } }
samples/mesh_shader_test/src/mesh_shader_test.zig
const std = @import( "std" ); const inf = std.math.inf; const min = std.math.min; const Allocator = std.mem.Allocator; usingnamespace @import( "../core/util.zig" ); usingnamespace @import( "../core/core.zig" ); usingnamespace @import( "../core/gtkz.zig" ); usingnamespace @import( "../core/support.zig" ); usingnamespace @import( "staticPaintable.zig" ); usingnamespace @import( "dots.zig" ); usingnamespace @import( "../time/cursor.zig" ); pub fn SpaceView( comptime N: usize, comptime P: usize ) type { return struct { const Self = @This(); glArea: *GtkWidget, axis0: Axis, axis1: Axis, bgPaintable: ClearPaintable, boxPaintable: StaticPaintable(4), dotsPaintable: DotsPaintable(N,P), axisUpdatingHandler: AxisUpdatingHandler(2), painters: [3]*Painter, paintingHandler: PaintingHandler, axisDraggable: AxisDraggable(2), draggers: [1]*Dragger, draggingHandler: DraggingHandler, // TODO: RLS would be better, but needs https://github.com/ziglang/zig/issues/2765 pub fn init( self: *Self, xLimits: *const [2]Interval, tCursor: *const VerticalCursor, allocator: *Allocator ) !void { self.glArea = gtk_gl_area_new( ); gtk_gl_area_set_required_version( @ptrCast( *GtkGLArea, self.glArea ), 3, 2 ); gtk_widget_set_events( self.glArea, GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_MOTION_MASK | GDK_BUTTON_RELEASE_MASK | GDK_SCROLL_MASK | GDK_SMOOTH_SCROLL_MASK | GDK_KEY_PRESS_MASK ); gtk_widget_set_can_focus( self.glArea, 1 ); self.axis0 = Axis.initBounds( -8.4, 8.4, 1 ); self.axis1 = Axis.initBounds( -6.4, 6.4, 1 ); self.bgPaintable = ClearPaintable.init( "SpaceView.bgPaintable", GL_COLOR_BUFFER_BIT ); self.bgPaintable.rgba = [4]GLfloat { 0.4, 0.4, 0.4, 1.0 }; var _axes = [2]*Axis { &self.axis0, &self.axis1 }; // TODO: Replace with aspect-ratio locking var _axesScale = inf( f64 ); for ( _axes ) |axis| { _axesScale = min( _axesScale, axis.scale ); } for ( _axes ) |axis| { axis.scale = _axesScale; } self.boxPaintable = StaticPaintable(4).init( "SpaceView.boxPaintable", _axes, GL_TRIANGLE_STRIP ); self.boxPaintable.rgba = [4]GLfloat { 0.0, 0.0, 0.0, 1.0 }; const xMin0 = @floatCast( GLfloat, xLimits[0].lowerBound( ).coord ); const xMax0 = @floatCast( GLfloat, xLimits[0].upperBound( ).coord ); const xMin1 = @floatCast( GLfloat, xLimits[1].lowerBound( ).coord ); const xMax1 = @floatCast( GLfloat, xLimits[1].upperBound( ).coord ); self.boxPaintable.vCoords = [8]GLfloat { xMin0,xMax1, xMin0,xMin1, xMax0,xMax1, xMax0,xMin1 }; self.boxPaintable.vCount = 4; self.dotsPaintable = DotsPaintable(N,P).init( "SpaceView.dotsPaintable", _axes, tCursor, allocator ); self.dotsPaintable.rgba = [4]GLfloat { 1.0, 0.0, 0.0, 1.0 }; self.axisUpdatingHandler = AxisUpdatingHandler(2).init( _axes, [2]u1 { 0, 1 } ); _ = try gtkzConnectHandler( self.glArea, "render", AxisUpdatingHandler(2).onRender, &self.axisUpdatingHandler ); _ = try gtkzConnectHandler( self.glArea, "scroll-event", AxisUpdatingHandler(2).onMouseWheel, &self.axisUpdatingHandler ); self.painters = [_]*Painter { &self.bgPaintable.painter, &self.boxPaintable.painter, &self.dotsPaintable.painter, }; self.paintingHandler = PaintingHandler.init( &self.painters ); _ = try gtkzConnectHandler( self.glArea, "render", PaintingHandler.onRender, &self.paintingHandler ); self.axisDraggable = AxisDraggable(2).init( _axes, [2]u1 { 0, 1 } ); self.draggers = [_]*Dragger { &self.axisDraggable.dragger, }; self.draggingHandler = try DraggingHandler.init( self.glArea, &self.draggers ); _ = try gtkzConnectHandler( self.glArea, "button-press-event", DraggingHandler.onMouseDown, &self.draggingHandler ); _ = try gtkzConnectHandler( self.glArea, "motion-notify-event", DraggingHandler.onMouseMove, &self.draggingHandler ); _ = try gtkzConnectHandler( self.glArea, "button-release-event", DraggingHandler.onMouseUp, &self.draggingHandler ); } pub fn deinit( self: *Self ) void { // FIXME: gtk_widget_destroy( self.glArea ); self.dotsPaintable.deinit( ); // FIXME: Disconnect signal handlers } }; }
src/space/view.zig
const std = @import("std"); const utils = @import("utils.zig"); pub const Error = utils.Error; const Guid = @This(); pub const size = 16; pub const string_size = 36; data: [size]u8 = undefined, pub fn is_null(self: *const Guid) bool { for (self.data) |b| { if (b != 0) { return false; } } return true; } pub fn equals(a: *const Guid, b: *const Guid) bool { return utils.memory_compare(&a.data, &b.data); } pub fn from_be(self: *Guid, source: []const u8) Error!void { if (source.len < size) { return Error.NotEnoughSource; } // 00112233-4455-6677-8899-AABBCCDDEEFF for (source[0..size]) |*ptr, i| { self.data[i] = ptr.*; } } pub fn new_from_be(source: []const u8) Error!Guid { var guid = Guid{}; try guid.from_be(source); return guid; } pub fn to_be(self: *const Guid, destination: []u8) Error!void { if (destination.len < size) { return Error.NotEnoughDestination; } for (destination[0..size]) |*ptr, i| { ptr.* = self.data[i]; } } pub fn from_ms(self: *Guid, source: []const u8) Error!void { if (source.len < size) { return Error.NotEnoughSource; } // 33221100-5544-7766-8899-AABBCCDDEEFF self.data[0x0] = source[0x3]; self.data[0x1] = source[0x2]; self.data[0x2] = source[0x1]; self.data[0x3] = source[0x0]; self.data[0x4] = source[0x5]; self.data[0x5] = source[0x4]; self.data[0x6] = source[0x7]; self.data[0x7] = source[0x6]; self.data[0x8] = source[0x8]; self.data[0x9] = source[0x9]; self.data[0xa] = source[0xa]; self.data[0xb] = source[0xb]; self.data[0xc] = source[0xc]; self.data[0xd] = source[0xd]; self.data[0xe] = source[0xe]; self.data[0xf] = source[0xf]; } pub fn new_from_ms(source: []const u8) Error!Guid { var guid = Guid{}; try guid.from_ms(source); return guid; } pub fn to_ms(self: *const Guid, destination: []u8) Error!void { if (destination.len < size) { return Error.NotEnoughDestination; } destination[0x3] = self.data[0x0]; destination[0x2] = self.data[0x1]; destination[0x1] = self.data[0x2]; destination[0x0] = self.data[0x3]; destination[0x5] = self.data[0x4]; destination[0x4] = self.data[0x5]; destination[0x7] = self.data[0x6]; destination[0x6] = self.data[0x7]; destination[0x8] = self.data[0x8]; destination[0x9] = self.data[0x9]; destination[0xa] = self.data[0xa]; destination[0xb] = self.data[0xb]; destination[0xc] = self.data[0xc]; destination[0xd] = self.data[0xd]; destination[0xe] = self.data[0xe]; destination[0xf] = self.data[0xf]; } pub fn to_string(self: *const Guid, buffer: []u8) Error!void { if (buffer.len < string_size) { return Error.NotEnoughDestination; } utils.byte_buffer(buffer[0..], self.data[0x0]); utils.byte_buffer(buffer[2..], self.data[0x1]); utils.byte_buffer(buffer[4..], self.data[0x2]); utils.byte_buffer(buffer[6..], self.data[0x3]); buffer[8] = '-'; utils.byte_buffer(buffer[9..], self.data[0x4]); utils.byte_buffer(buffer[11..], self.data[0x5]); buffer[13] = '-'; utils.byte_buffer(buffer[14..], self.data[0x6]); utils.byte_buffer(buffer[16..], self.data[0x7]); buffer[18] = '-'; utils.byte_buffer(buffer[19..], self.data[0x8]); utils.byte_buffer(buffer[21..], self.data[0x9]); buffer[23] = '-'; utils.byte_buffer(buffer[24..], self.data[0xa]); utils.byte_buffer(buffer[26..], self.data[0xb]); utils.byte_buffer(buffer[28..], self.data[0xc]); utils.byte_buffer(buffer[30..], self.data[0xd]); utils.byte_buffer(buffer[32..], self.data[0xe]); utils.byte_buffer(buffer[34..], self.data[0xf]); } const test_guid_source = "\x28\x73\x2a\xc1\x1f\xf8\xd2\x11\xba\x4b\x00\xa0\xc9\x3e\xc9\x3b"; test "MS Guid" { const guid = try new_from_ms(test_guid_source); var guid_string: [string_size]u8 = undefined; try guid.to_string(guid_string[0..]); try std.testing.expectEqualStrings("c12a7328-f81f-11d2-ba4b-00a0c93ec93b", &guid_string); var guid_dst: [size]u8 = undefined; try guid.to_ms(&guid_dst); try std.testing.expectEqualSlices(u8, test_guid_source, &guid_dst); } test "BE Guid" { const guid = try new_from_be(test_guid_source); var guid_string: [string_size]u8 = undefined; try guid.to_string(guid_string[0..]); try std.testing.expectEqualStrings("28732ac1-1ff8-d211-ba4b-00a0c93ec93b", &guid_string); var guid_dst: [size]u8 = undefined; try guid.to_be(&guid_dst); try std.testing.expectEqualSlices(u8, test_guid_source, &guid_dst); }
libs/utils/guid.zig
const std = @import("std"); const builtin = @import("builtin"); const Allocator = mem.Allocator; const Decl = @import("decl.zig").Decl; const Compilation = @import("compilation.zig").Compilation; const mem = std.mem; const ast = std.zig.ast; const Value = @import("value.zig").Value; const Type = @import("type.zig").Type; const ir = @import("ir.zig"); const Span = @import("errmsg.zig").Span; const assert = std.debug.assert; const event = std.event; const llvm = @import("llvm.zig"); pub const Scope = struct { id: Id, parent: ?*Scope, ref_count: std.atomic.Int(usize), /// Thread-safe pub fn ref(base: *Scope) void { _ = base.ref_count.incr(); } /// Thread-safe pub fn deref(base: *Scope, comp: *Compilation) void { if (base.ref_count.decr() == 1) { if (base.parent) |parent| parent.deref(comp); switch (base.id) { Id.Root => @fieldParentPtr(Root, "base", base).destroy(comp), Id.Decls => @fieldParentPtr(Decls, "base", base).destroy(comp), Id.Block => @fieldParentPtr(Block, "base", base).destroy(comp), Id.FnDef => @fieldParentPtr(FnDef, "base", base).destroy(comp), Id.CompTime => @fieldParentPtr(CompTime, "base", base).destroy(comp), Id.Defer => @fieldParentPtr(Defer, "base", base).destroy(comp), Id.DeferExpr => @fieldParentPtr(DeferExpr, "base", base).destroy(comp), Id.Var => @fieldParentPtr(Var, "base", base).destroy(comp), Id.AstTree => @fieldParentPtr(AstTree, "base", base).destroy(comp), } } } pub fn findRoot(base: *Scope) *Root { var scope = base; while (scope.parent) |parent| { scope = parent; } assert(scope.id == Id.Root); return @fieldParentPtr(Root, "base", scope); } pub fn findFnDef(base: *Scope) ?*FnDef { var scope = base; while (true) { switch (scope.id) { Id.FnDef => return @fieldParentPtr(FnDef, "base", scope), Id.Root, Id.Decls => return null, Id.Block, Id.Defer, Id.DeferExpr, Id.CompTime, Id.Var, => scope = scope.parent.?, Id.AstTree => unreachable, } } } pub fn findDeferExpr(base: *Scope) ?*DeferExpr { var scope = base; while (true) { switch (scope.id) { Id.DeferExpr => return @fieldParentPtr(DeferExpr, "base", scope), Id.FnDef, Id.Decls, => return null, Id.Block, Id.Defer, Id.CompTime, Id.Root, Id.Var, => scope = scope.parent orelse return null, Id.AstTree => unreachable, } } } fn init(base: *Scope, id: Id, parent: *Scope) void { base.* = Scope{ .id = id, .parent = parent, .ref_count = std.atomic.Int(usize).init(1), }; parent.ref(); } pub const Id = enum { Root, AstTree, Decls, Block, FnDef, CompTime, Defer, DeferExpr, Var, }; pub const Root = struct { base: Scope, realpath: []const u8, decls: *Decls, /// Creates a Root scope with 1 reference /// Takes ownership of realpath pub fn create(comp: *Compilation, realpath: []u8) !*Root { const self = try comp.gpa().create(Root); self.* = Root{ .base = Scope{ .id = Id.Root, .parent = null, .ref_count = std.atomic.Int(usize).init(1), }, .realpath = realpath, .decls = undefined, }; errdefer comp.gpa().destroy(self); self.decls = try Decls.create(comp, &self.base); return self; } pub fn destroy(self: *Root, comp: *Compilation) void { // TODO comp.fs_watch.removeFile(self.realpath); self.decls.base.deref(comp); comp.gpa().free(self.realpath); comp.gpa().destroy(self); } }; pub const AstTree = struct { base: Scope, tree: *ast.Tree, /// Creates a scope with 1 reference /// Takes ownership of tree, will deinit and destroy when done. pub fn create(comp: *Compilation, tree: *ast.Tree, root_scope: *Root) !*AstTree { const self = try comp.gpa().create(AstTree); self.* = AstTree{ .base = undefined, .tree = tree, }; self.base.init(Id.AstTree, &root_scope.base); return self; } pub fn destroy(self: *AstTree, comp: *Compilation) void { comp.gpa().free(self.tree.source); self.tree.deinit(); comp.gpa().destroy(self.tree); comp.gpa().destroy(self); } pub fn root(self: *AstTree) *Root { return self.base.findRoot(); } }; pub const Decls = struct { base: Scope, /// This table remains Write Locked when the names are incomplete or possibly outdated. /// So if a reader manages to grab a lock, it can be sure that the set of names is complete /// and correct. table: event.RwLocked(Decl.Table), /// Creates a Decls scope with 1 reference pub fn create(comp: *Compilation, parent: *Scope) !*Decls { const self = try comp.gpa().create(Decls); self.* = Decls{ .base = undefined, .table = event.RwLocked(Decl.Table).init(comp.loop, Decl.Table.init(comp.gpa())), }; self.base.init(Id.Decls, parent); return self; } pub fn destroy(self: *Decls, comp: *Compilation) void { self.table.deinit(); comp.gpa().destroy(self); } }; pub const Block = struct { base: Scope, incoming_values: std.ArrayList(*ir.Inst), incoming_blocks: std.ArrayList(*ir.BasicBlock), end_block: *ir.BasicBlock, is_comptime: *ir.Inst, safety: Safety, const Safety = union(enum) { Auto, Manual: Manual, const Manual = struct { /// the source span that disabled the safety value span: Span, /// whether safety is enabled enabled: bool, }; fn get(self: Safety, comp: *Compilation) bool { return switch (self) { Safety.Auto => switch (comp.build_mode) { builtin.Mode.Debug, builtin.Mode.ReleaseSafe, => true, builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall, => false, }, @TagType(Safety).Manual => |man| man.enabled, }; } }; /// Creates a Block scope with 1 reference pub fn create(comp: *Compilation, parent: *Scope) !*Block { const self = try comp.gpa().create(Block); self.* = Block{ .base = undefined, .incoming_values = undefined, .incoming_blocks = undefined, .end_block = undefined, .is_comptime = undefined, .safety = Safety.Auto, }; self.base.init(Id.Block, parent); return self; } pub fn destroy(self: *Block, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const FnDef = struct { base: Scope, /// This reference is not counted so that the scope can get destroyed with the function fn_val: ?*Value.Fn, /// Creates a FnDef scope with 1 reference /// Must set the fn_val later pub fn create(comp: *Compilation, parent: *Scope) !*FnDef { const self = try comp.gpa().create(FnDef); self.* = FnDef{ .base = undefined, .fn_val = null, }; self.base.init(Id.FnDef, parent); return self; } pub fn destroy(self: *FnDef, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const CompTime = struct { base: Scope, /// Creates a CompTime scope with 1 reference pub fn create(comp: *Compilation, parent: *Scope) !*CompTime { const self = try comp.gpa().create(CompTime); self.* = CompTime{ .base = undefined }; self.base.init(Id.CompTime, parent); return self; } pub fn destroy(self: *CompTime, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Defer = struct { base: Scope, defer_expr_scope: *DeferExpr, kind: Kind, pub const Kind = enum { ScopeExit, ErrorExit, }; /// Creates a Defer scope with 1 reference pub fn create( comp: *Compilation, parent: *Scope, kind: Kind, defer_expr_scope: *DeferExpr, ) !*Defer { const self = try comp.gpa().create(Defer); self.* = Defer{ .base = undefined, .defer_expr_scope = defer_expr_scope, .kind = kind, }; self.base.init(Id.Defer, parent); defer_expr_scope.base.ref(); return self; } pub fn destroy(self: *Defer, comp: *Compilation) void { self.defer_expr_scope.base.deref(comp); comp.gpa().destroy(self); } }; pub const DeferExpr = struct { base: Scope, expr_node: *ast.Node, reported_err: bool, /// Creates a DeferExpr scope with 1 reference pub fn create(comp: *Compilation, parent: *Scope, expr_node: *ast.Node) !*DeferExpr { const self = try comp.gpa().create(DeferExpr); self.* = DeferExpr{ .base = undefined, .expr_node = expr_node, .reported_err = false, }; self.base.init(Id.DeferExpr, parent); return self; } pub fn destroy(self: *DeferExpr, comp: *Compilation) void { comp.gpa().destroy(self); } }; pub const Var = struct { base: Scope, name: []const u8, src_node: *ast.Node, data: Data, pub const Data = union(enum) { Param: Param, Const: *Value, }; pub const Param = struct { index: usize, typ: *Type, llvm_value: *llvm.Value, }; pub fn createParam( comp: *Compilation, parent: *Scope, name: []const u8, src_node: *ast.Node, param_index: usize, param_type: *Type, ) !*Var { const self = try create(comp, parent, name, src_node); self.data = Data{ .Param = Param{ .index = param_index, .typ = param_type, .llvm_value = undefined, }, }; return self; } pub fn createConst( comp: *Compilation, parent: *Scope, name: []const u8, src_node: *ast.Node, value: *Value, ) !*Var { const self = try create(comp, parent, name, src_node); self.data = Data{ .Const = value }; value.ref(); return self; } fn create(comp: *Compilation, parent: *Scope, name: []const u8, src_node: *ast.Node) !*Var { const self = try comp.gpa().create(Var); self.* = Var{ .base = undefined, .name = name, .src_node = src_node, .data = undefined, }; self.base.init(Id.Var, parent); return self; } pub fn destroy(self: *Var, comp: *Compilation) void { switch (self.data) { Data.Param => {}, Data.Const => |value| value.deref(comp), } comp.gpa().destroy(self); } }; };
src-self-hosted/scope.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { const exe = b.addExecutable("async-lpc", "src/main.zig"); exe.addPackage(std.build.Pkg{ .name = "lpc1768", .path = "libs/lpc1768/lpc1768.zig", }); exe.setTarget(std.zig.CrossTarget{ .cpu_arch = .thumb, .cpu_model = .{ .explicit = &std.Target.arm.cpu.cortex_m3, }, .os_tag = .freestanding, .abi = .eabi, }); exe.strip = true; exe.setBuildMode(.ReleaseSmall); exe.install(); exe.setLinkerScriptPath("./src/linker.ld"); const create_hex = b.addSystemCommand(&[_][]const u8{ "arm-none-eabi-objcopy", "-R", "stack", "-R", ".data", "-R", ".bss", "-R", ".debug_abbrev", "-O", "ihex", // "zig-cache/bin/async-lpc", // "async-lpc.hex", }); create_hex.addArtifactArg(exe); create_hex.addArg("firmware.hex"); const hex_step = b.step("hex", "Creates a flashable ihex file"); hex_step.dependOn(&create_hex.step); const create_bin = b.addSystemCommand(&[_][]const u8{ "arm-none-eabi-objcopy", "-I", "ihex", "-O", "binary", "firmware.hex", "firmware.bin", }); create_bin.step.dependOn(&create_hex.step); const bin_step = b.step("bin", "Creates a flashable binary file"); bin_step.dependOn(&create_bin.step); const flash_step = b.step("flash", "Creates a hex file and flashes it."); if (b.option([]const u8, "flash-drive", "If given, the file is deployed via mtools/fat32")) |file_name| { const copy_flash = b.addSystemCommand(&[_][]const u8{ "mcopy", "-D", "o", // override the file without asking "firmware.bin", // from firmware.bin "::firmware.bin", // to D:\firmware.bin "-i", // MUST BE LAST }); copy_flash.addArg(file_name); copy_flash.step.dependOn(&create_bin.step); flash_step.dependOn(&copy_flash.step); } else { // This is 100% machine dependant const run_flash = b.addSystemCommand(&[_][]const u8{ "flash-magic", "COM(5, 115200)", "DEVICE(LPC1768, 0.000000, 0)", "HARDWARE(BOOTEXEC, 50, 100)", "ERASEUSED(Z:\\home\\felix\\projects\\lowlevel\\async-lpc\\async-lpc.hex, PROTECTISP)", "HEXFILE(Z:\\home\\felix\\projects\\lowlevel\\async-lpc\\async-lpc.hex, NOCHECKSUMS, NOFILL, PROTECTISP)", }); run_flash.step.dependOn(&create_hex.step); flash_step.dependOn(&run_flash.step); } const run_term = b.addSystemCommand(&[_][]const u8{ "picocom", "--baud", "19200", "--lower-rts", // Disable programmer "--lower-dtr", // Disable reset "/dev/ttyUSB0", }); const term_step = b.step("terminal", "Starts picocom on the correct port"); term_step.dependOn(&run_term.step); }
research-chamber/build.zig
const std = @import("std"); const math = std.math; const testing = std.testing; fn reflect(comptime UInt: type, data: UInt) UInt { const bits = @typeInfo(UInt).Int.bits; var res: UInt = 0; var tmp = data; var bit: usize = 0; while (bit < bits) : (bit += 1) { if (tmp & 1 != 0) { res |= math.shl(UInt, 1, ((bits - 1) - bit)); } tmp >>= 1; } return res; } test "crc.reflect" { try testing.expectEqual(@as(u8, 0b10000000), reflect(u8, 0b00000001)); try testing.expectEqual(@as(u8, 0b00000001), reflect(u8, 0b10000000)); } pub const crcspec_init_backward_cycles = 20000; pub const Reflect = struct { pub const Data = enum { True, False, }; pub const Remainder = enum { True, False, }; }; pub fn CrcSpec(comptime UInt: type) type { return struct { polynomial: UInt, initial_value: UInt, xor_value: UInt, reflect_data: bool, reflect_remainder: bool, table: [256]UInt = undefined, pub fn init(polynomial: UInt, initial_value: UInt, xor_value: UInt, reflect_data: bool, reflect_remainder: bool) CrcSpec(UInt) { var res = @This(){ .polynomial = polynomial, .initial_value = initial_value, .xor_value = xor_value, .reflect_data = reflect_data, .reflect_remainder = reflect_remainder, .table = undefined, }; const bits = @typeInfo(UInt).Int.bits; const top_bit = @as(UInt, 1) << (bits - 1); for (res.table) |*entry, i| { var crc = @intCast(UInt, i) << (bits - 8); var bit: usize = 0; while (bit < 8) : (bit += 1) { if (crc & top_bit != 0) { crc = math.shl(UInt, crc, @as(UInt, 1)) ^ polynomial; } else { crc = math.shl(UInt, crc, @as(UInt, 1)); } } entry.* = crc; } return res; } pub fn checksum(spec: @This(), bytes: []const u8) UInt { var crc = spec.processer(); crc.update(bytes); return crc.final(); } pub fn processer(spec: @This()) Crc(UInt) { return Crc(UInt).init(spec); } }; } pub fn Crc(comptime UInt: type) type { return struct { const bits = @typeInfo(UInt).Int.bits; spec: CrcSpec(UInt), remainder: UInt, pub fn init(spec: CrcSpec(UInt)) @This() { return @This(){ .spec = spec, .remainder = spec.initial_value, }; } fn reflect_if(comptime K: type, ref: bool, data: K) K { if (ref) { return reflect(K, data); } else { return data; } } pub fn update(crc: *@This(), bytes: []const u8) void { for (bytes) |byte| { const entry = reflect_if(u8, crc.spec.reflect_data, byte) ^ (crc.remainder >> (bits - 8)); crc.remainder = crc.spec.table[entry] ^ math.shl(UInt, crc.remainder, @as(UInt, 8)); } } pub fn final(crc: @This()) UInt { const reflected = reflect_if(UInt, crc.spec.reflect_remainder, crc.remainder); return reflected ^ crc.spec.xor_value; } }; } // Specs below gotten from http://reveng.sourceforge.net/crc-catalogue/all.htm pub const crc8 = blk: { @setEvalBranchQuota(crcspec_init_backward_cycles); break :blk CrcSpec(u8).init(0x07, 0x00, 0x00, false, false); }; test "crc.crc8" { try testing.expectEqual(@as(u8, 0xF4), crc8.checksum("123456789")); } pub const crc16 = blk: { @setEvalBranchQuota(crcspec_init_backward_cycles); break :blk CrcSpec(u16).init(0x8005, 0x0000, 0x0000, true, true); }; test "crc.crc16" { try testing.expectEqual(@as(u16, 0xBB3D), crc16.checksum("123456789")); } pub const crc32 = blk: { @setEvalBranchQuota(crcspec_init_backward_cycles); break :blk CrcSpec(u32).init(0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true); }; test "crc.crc32" { try testing.expectEqual(@as(u32, 0xCBF43926), crc32.checksum("123456789")); } pub const crc64 = blk: { @setEvalBranchQuota(crcspec_init_backward_cycles); break :blk CrcSpec(u64).init(0x42F0E1EBA9EA3693, 0x0000000000000000, 0x0000000000000000, false, false); }; test "crc.crc64" { try testing.expectEqual(@as(u64, 0x6C40DF5F0B497347), crc64.checksum("123456789")); }
crc.zig
const std = @import("std"); const log = std.log; const math = std.math; const testing = std.testing; const assert = std.debug.assert; const cuda = @import("cudaz"); const cu = cuda.cu; const png = @import("png.zig"); const utils = @import("utils.zig"); const resources_dir = "resources/hw3_resources/"; pub fn main() !void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = general_purpose_allocator.allocator(); var stream = try cuda.Stream.init(0); defer stream.deinit(); log.info("***** HW3 ******", .{}); const img = try png.Image.fromFilePath(allocator, resources_dir ++ "/memorial_exr.png"); const numRows = img.height; const numCols = img.width; const rgb = try asFloat32(allocator, img); img.deinit(); // load the image and convert it to xyY format const d_rgb = try cuda.allocAndCopy(cu.float3, rgb); const d_xyY = try cuda.alloc(cu.float3, numCols * numRows); const threads = cuda.Dim3.init(32, 16, 1); const blocks = cuda.Dim3.init((numCols + threads.x - 1) / threads.x, (numRows + threads.y - 1) / threads.y, 1); const grid = cuda.Grid{ .blocks = blocks, .threads = threads }; const rgb_to_xyY = try cuda.Function("rgb_to_xyY").init(); try rgb_to_xyY.launch(&stream, grid, .{ d_rgb.ptr, d_xyY.ptr, 0.0001, @intCast(c_int, numRows), @intCast(c_int, numCols), }); const h_xyY = try allocator.alloc(cu.float3, numCols * numRows); try cuda.memcpyDtoH(cu.float3, h_xyY, d_xyY); // allocate memory for the cdf of the histogram const numBins: usize = 1024; var d_cdf = try cuda.alloc(f32, numBins); defer cuda.free(d_cdf); var timer = cuda.GpuTimer.start(&stream); errdefer timer.deinit(); const min_max_lum = try histogram_and_prefixsum(&stream, d_xyY, d_cdf, numRows, numCols, numBins); var lum_min = min_max_lum.x; var lum_range = min_max_lum.y - min_max_lum.x; timer.stop(); stream.synchronize(); std.log.info("Your code ran in: {d:.1} msecs.", .{timer.elapsed() * 1000}); std.log.info("Found a lum range of: {d:.5}", .{min_max_lum}); var h_cdf = try cuda.allocAndCopyResult(f32, allocator, d_cdf); std.log.info("Lum cdf: {d:.3}", .{h_cdf}); const tone_map = try cuda.Function("tone_map").init(); try tone_map.launch( &stream, grid, .{ d_xyY.ptr, d_cdf.ptr, d_rgb.ptr, lum_min, lum_range, numBins, @intCast(c_int, numRows), @intCast(c_int, numCols), }, ); try cuda.memcpyDtoH(cu.float3, rgb, d_rgb); var out_img = try fromFloat32(allocator, rgb, numCols, numRows); defer out_img.deinit(); try out_img.writeToFilePath(resources_dir ++ "output.png"); try utils.validate_output(allocator, resources_dir, 2.0); try std.testing.expect(lum_range > 0); } fn asFloat32(allocator: std.mem.Allocator, img: png.Image) ![]cu.float3 { var rgb = try allocator.alloc(cu.float3, img.width * img.height); var pixels = img.iterator(); var i: usize = 0; while (pixels.next()) |color| : (i += 1) { rgb[i] = .{ .x = color.r, .y = color.g, .z = color.b, }; } return rgb; } pub inline fn toColorIntClamp(comptime T: type, value: f32) T { if (math.isNan(value)) return 0; var val = value; var max_val = @intToFloat(f32, math.maxInt(T)); var min_val = @intToFloat(f32, math.minInt(T)); val = math.max(min_val, math.min(max_val, val * max_val)); return @floatToInt(T, math.round(val)); } fn fromFloat32(allocator: std.mem.Allocator, rgb: []cu.float3, width: usize, height: usize) !png.Image { var pixels = try allocator.alloc(png.Rgb24, width * height); for (rgb) |value, i| { pixels[i] = png.Rgb24{ .r = toColorIntClamp(u8, value.x), .g = toColorIntClamp(u8, value.y), .b = toColorIntClamp(u8, value.z), }; // if (i % 100 == 0) { // log.debug("{} -> {}", .{ value, pixels[i] }); // } } return png.Image{ .allocator = allocator, .width = @intCast(u32, width), .height = @intCast(u32, height), .px = .{ .rgb24 = pixels }, }; } fn histogram_and_prefixsum( stream: *cuda.Stream, d_xyY: []const cu.float3, d_cdf: []f32, numRows: usize, numCols: usize, numBins: usize, ) !cu.float2 { // Here are the steps you need to implement // 1) find the minimum and maximum value in the input logLuminance channel // store in min_logLum and max_logLum // 2) subtract them to find the range // 3) generate a histogram of all the values in the logLuminance channel using // the formula: bin = (lum[i] - lumMin) / lumRange * numBins // 4) Perform an exclusive scan (prefix sum) on the histogram to get // the cumulative distribution of luminance values (this should go in the // incoming d_cdf pointer which already has been allocated for you) var num_pixels = numRows * numCols; var min_max_lum = try reduceMinMaxLum(stream, d_xyY); const lumHisto = try cuda.Function("lum_histo").init(); var d_histo = try cuda.alloc(c_uint, numBins); try cuda.memset(c_uint, d_histo, 0); try lumHisto.launch( stream, cuda.Grid.init1D(num_pixels, 1024), .{ d_histo.ptr, d_xyY.ptr, min_max_lum.x, min_max_lum.y - min_max_lum.x, @intCast(c_int, numBins), @intCast(c_int, num_pixels), }, ); const computeCdf = try cuda.Function("blellochCdf").init(); try computeCdf.launch( stream, cuda.Grid.init1D(numBins, numBins), .{ d_cdf.ptr, d_histo.ptr, @intCast(c_int, numBins) }, ); stream.synchronize(); return min_max_lum; } fn reduceMinMaxLum( stream: *cuda.Stream, d_xyY: []const cu.float3, ) !cu.float2 { // TODO: the results seems to change between runs const num_pixels = d_xyY.len; const reduce_minmax_lum = try cuda.Function("reduce_minmax_lum").init(); const grid = cuda.Grid.init1D(num_pixels, 1024); var d_buff = try cuda.alloc(cu.float2, grid.blocks.x); defer cuda.free(d_buff); var d_min_max_lum = try cuda.alloc(cu.float2, 1); try cuda.memsetD8(cu.float2, d_min_max_lum, 0xaa); defer cuda.free(d_min_max_lum); try reduce_minmax_lum.launchWithSharedMem( stream, grid, grid.threads.x * @sizeOf(cu.float2), .{ d_xyY.ptr, d_buff.ptr, @intCast(c_int, num_pixels) }, ); const one_block = cuda.Grid.init1D(d_buff.len, 0); const reduce_minmax = try cuda.Function("reduce_minmax").init(); try reduce_minmax.launchWithSharedMem( stream, one_block, one_block.threads.x * @sizeOf(cu.float2), .{ d_buff.ptr, d_min_max_lum.ptr }, ); var min_max_lum = try cuda.readResult(cu.float2, &d_min_max_lum[0]); try std.testing.expect(min_max_lum.x < min_max_lum.y); return min_max_lum; } fn z(_z: f32) cu.float3 { return cu.float3{ .x = 0.0, .y = 0.0, .z = _z }; } test "histogram" { var stream = try cuda.Stream.init(0); var img = [_]cu.float3{ z(0.0), z(0.0), z(1.0), z(2.0), z(3.0), z(4.0), z(6.0), z(7.0), z(8.0), z(9.0), z(3.0), z(3.0), z(3.0), z(9.0), z(10.0), }; const lumHisto = try cuda.Function("lum_histo").init(); var bins = [_]c_uint{0} ** 10; var d_img = try cuda.allocAndCopy(cu.float3, &img); var d_bins = try cuda.allocAndCopy(c_uint, &bins); try lumHisto.launch( &stream, cuda.Grid.init1D(img.len, 3), .{ d_bins.ptr, d_img.ptr, 0, 9, @intCast(c_int, bins.len), @intCast(c_int, img.len), }, ); try cuda.memcpyDtoH(c_uint, &bins, d_bins); std.log.warn("bins: {any}", .{bins}); try std.testing.expectEqual( [10]c_uint{ 2, 1, 1, 4, 1, 0, 1, 1, 1, 3 }, bins, ); } const ReduceMinmaxLum = cuda.Function("reduce_minmax_lum"); fn test_min_max_lum(stream: *cuda.Stream, f: ReduceMinmaxLum, d_img: []cu.float3, expected: []const cu.float2) !void { var num_blocks = expected.len; var d_minmax = try cuda.alloc(cu.float2, num_blocks); defer cuda.free(d_minmax); var grid1D = cuda.Grid{ .blocks = .{ .x = @intCast(c_uint, num_blocks) }, .threads = .{ .x = @intCast(c_uint, std.math.divCeil(usize, d_img.len, num_blocks) catch unreachable) }, }; try f.launchWithSharedMem( stream, grid1D, @sizeOf(cu.float2) * grid1D.threads.x, .{ d_img.ptr, d_minmax.ptr, @intCast(c_int, d_img.len), }, ); var minmax = try cuda.allocAndCopyResult(cu.float2, testing.allocator, d_minmax); defer testing.allocator.free(minmax); std.log.warn("minmax ({}x{}): {any}", .{ grid1D.blocks.x, grid1D.threads.x, minmax }); for (expected) |exp, index| { std.testing.expectEqual(exp, minmax[index]) catch |err| { switch (err) { error.TestExpectedEqual => log.err("At index {} expected {d:.0} got {d:.0}", .{ index, exp, minmax[index] }), else => {}, } return err; }; } } test "min_max_lum" { var stream = try cuda.Stream.init(0); var img = [_]cu.float3{ z(0), z(3), z(0), z(1), z(2), z(4), z(6), z(7), z(8), z(9), z(10), z(3), z(3), z(3), z(9), z(3), }; const f = try ReduceMinmaxLum.init(); var d_img = try cuda.allocAndCopy(cu.float3, &img); try test_min_max_lum(&stream, f, d_img, &[_]cu.float2{ .{ .x = 0, .y = 7 }, .{ .x = 3, .y = 10 }, }); try test_min_max_lum(&stream, f, d_img, &[_]cu.float2{ .{ .x = 0, .y = 3 }, .{ .x = 2, .y = 7 }, .{ .x = 3, .y = 10 }, .{ .x = 3, .y = 9 }, }); } test "cdf" { var stream = try cuda.Stream.init(0); inline for ([_][:0]const u8{ "computeCdf", "blellochCdf" }) |variant| { log.warn("Testing Cdf implementation: {s}", .{variant}); var bins = [_]c_uint{ 2, 1, 1, 4, 1, 0, 1, 1, 1, 3 }; const computeCdf = try cuda.Function(variant).init(); var cdf = [_]f32{0.0} ** 10; var d_bins = try cuda.allocAndCopy(c_uint, &bins); var d_cdf = try cuda.allocAndCopy(f32, &cdf); try computeCdf.launch( &stream, cuda.Grid.init1D(bins.len, 0), .{ d_cdf.ptr, d_bins.ptr, @intCast(c_int, bins.len), }, ); try cuda.memcpyDtoH(f32, &cdf, d_cdf); try cuda.memcpyDtoH(c_uint, &bins, d_bins); var t: f32 = 15.0; const tgt_cdf = [10]f32{ 0, 2 / t, 3 / t, 4 / t, 8 / t, 9 / t, 9 / t, 10 / t, 11 / t, 12 / t }; log.warn("bins: {d}", .{bins}); log.warn("tgt_cdf: {d:.3}", .{tgt_cdf}); log.warn("cdf: {d:.3}", .{cdf}); var i: u8 = 0; while (i < cdf.len) : (i += 1) { try std.testing.expectApproxEqRel(tgt_cdf[i], cdf[i], 0.0001); } } }
CS344/src/hw3.zig
const std = @import("std"); const assert = std.debug.assert; const glfw = @import("glfw"); const gpu = @import("gpu"); const c = @import("c.zig").c; const objc = @cImport({ @cInclude("objc/message.h"); }); fn printUnhandledError(_: void, typ: gpu.ErrorType, message: [*:0]const u8) void { switch (typ) { .validation => std.debug.print("gpu: validation error: {s}\n", .{message}), .out_of_memory => std.debug.print("gpu: out of memory: {s}\n", .{message}), .device_lost => std.debug.print("gpu: device lost: {s}\n", .{message}), .unknown => std.debug.print("gpu: unknown error: {s}\n", .{message}), else => unreachable, } } var printUnhandledErrorCallback = gpu.ErrorCallback.init(void, {}, printUnhandledError); const Setup = struct { native_instance: gpu.NativeInstance, backend_type: gpu.Adapter.BackendType, device: gpu.Device, window: glfw.Window, }; fn getEnvVarOwned(allocator: std.mem.Allocator, key: []const u8) error{ OutOfMemory, InvalidUtf8 }!?[]u8 { return std.process.getEnvVarOwned(allocator, key) catch |err| switch (err) { error.EnvironmentVariableNotFound => @as(?[]u8, null), else => |e| e, }; } fn detectBackendType(allocator: std.mem.Allocator) !gpu.Adapter.BackendType { const GPU_BACKEND = try getEnvVarOwned(allocator, "GPU_BACKEND"); if (GPU_BACKEND) |backend| { defer allocator.free(backend); if (std.ascii.eqlIgnoreCase(backend, "opengl")) return .opengl; if (std.ascii.eqlIgnoreCase(backend, "opengles")) return .opengles; if (std.ascii.eqlIgnoreCase(backend, "d3d11")) return .d3d11; if (std.ascii.eqlIgnoreCase(backend, "d3d12")) return .d3d12; if (std.ascii.eqlIgnoreCase(backend, "metal")) return .metal; if (std.ascii.eqlIgnoreCase(backend, "null")) return .nul; if (std.ascii.eqlIgnoreCase(backend, "vulkan")) return .vulkan; @panic("unknown BACKEND type"); } const target = @import("builtin").target; if (target.isDarwin()) return .metal; if (target.os.tag == .windows) return .d3d12; return .vulkan; } pub fn setup(allocator: std.mem.Allocator) !Setup { const backend_type = try detectBackendType(allocator); try glfw.init(.{}); // Create the test window and discover adapters using it (esp. for OpenGL) var hints = glfwWindowHintsForBackend(backend_type); hints.cocoa_retina_framebuffer = true; const window = try glfw.Window.create(640, 480, "mach/gpu window", null, null, hints); const backend_procs = c.machDawnNativeGetProcs(); c.dawnProcSetProcs(backend_procs); const instance = c.machDawnNativeInstance_init(); var native_instance = gpu.NativeInstance.wrap(c.machDawnNativeInstance_get(instance).?); // Discovers e.g. OpenGL adapters. try discoverAdapters(instance, window, backend_type); // Request an adapter. // // TODO: It would be nice if we could use gpu_interface.waitForAdapter here, however the webgpu.h // API does not yet have a way to specify what type of backend you want (vulkan, opengl, etc.) // In theory, I suppose we shouldn't need to and Dawn should just pick the best adapter - but in // practice if Vulkan is not supported today waitForAdapter/requestAdapter merely generates an error. // // const gpu_interface = native_instance.interface(); // const backend_adapter = switch (gpu_interface.waitForAdapter(&.{ // .power_preference = .high_performance, // })) { // .adapter => |v| v, // .err => |err| { // std.debug.print("failed to get adapter: error={} {s}\n", .{ err.code, err.message }); // std.process.exit(1); // }, // }; const adapters = c.machDawnNativeInstance_getAdapters(instance); var dawn_adapter: ?c.MachDawnNativeAdapter = null; var i: usize = 0; while (i < c.machDawnNativeAdapters_length(adapters)) : (i += 1) { const adapter = c.machDawnNativeAdapters_index(adapters, i); const properties = c.machDawnNativeAdapter_getProperties(adapter); const found_backend_type = @intToEnum(gpu.Adapter.BackendType, c.machDawnNativeAdapterProperties_getBackendType(properties)); if (found_backend_type == backend_type) { dawn_adapter = adapter; } } if (dawn_adapter == null) { std.debug.print("no matching adapter found for {s}", .{@tagName(backend_type)}); std.debug.print("-> maybe try GPU_BACKEND=opengl ?\n", .{}); std.process.exit(1); } assert(dawn_adapter != null); const backend_adapter = gpu.NativeInstance.fromWGPUAdapter(c.machDawnNativeAdapter_get(dawn_adapter.?).?); // Print which adapter we are going to use. const props = backend_adapter.properties; std.debug.print("found {s} backend on {s} adapter: {s}, {s}\n", .{ gpu.Adapter.backendTypeName(props.backend_type), gpu.Adapter.typeName(props.adapter_type), props.name, props.driver_description, }); const device = switch (backend_adapter.waitForDevice(&.{})) { .device => |v| v, .err => |err| { std.debug.print("failed to get device: error={} {s}\n", .{ err.code, err.message }); std.process.exit(1); }, }; device.setUncapturedErrorCallback(&printUnhandledErrorCallback); return Setup{ .native_instance = native_instance, .backend_type = backend_type, .device = device, .window = window, }; } fn glfwWindowHintsForBackend(backend: gpu.Adapter.BackendType) glfw.Window.Hints { return switch (backend) { .opengl => .{ // Ask for OpenGL 4.4 which is what the GL backend requires for compute shaders and // texture views. .context_version_major = 4, .context_version_minor = 4, .opengl_forward_compat = true, .opengl_profile = .opengl_core_profile, }, .opengles => .{ .context_version_major = 3, .context_version_minor = 1, .client_api = .opengl_es_api, .context_creation_api = .egl_context_api, }, else => .{ // Without this GLFW will initialize a GL context on the window, which prevents using // the window with other APIs (by crashing in weird ways). .client_api = .no_api, }, }; } fn discoverAdapters(instance: c.MachDawnNativeInstance, window: glfw.Window, typ: gpu.Adapter.BackendType) !void { switch (typ) { .opengl => { try glfw.makeContextCurrent(window); const adapter_options = c.MachDawnNativeAdapterDiscoveryOptions_OpenGL{ .getProc = @ptrCast(fn ([*c]const u8) callconv(.C) ?*anyopaque, glfw.getProcAddress), }; _ = c.machDawnNativeInstance_discoverAdapters(instance, @enumToInt(typ), &adapter_options); }, .opengles => { try glfw.makeContextCurrent(window); const adapter_options = c.MachDawnNativeAdapterDiscoveryOptions_OpenGLES{ .getProc = @ptrCast(fn ([*c]const u8) callconv(.C) ?*anyopaque, glfw.getProcAddress), }; _ = c.machDawnNativeInstance_discoverAdapters(instance, @enumToInt(typ), &adapter_options); }, else => { c.machDawnNativeInstance_discoverDefaultAdapters(instance); }, } } pub fn detectGLFWOptions() glfw.BackendOptions { const target = @import("builtin").target; if (target.isDarwin()) return .{ .cocoa = true }; return switch (target.os.tag) { .windows => .{ .win32 = true }, .linux => .{ .x11 = true }, else => .{}, }; } pub fn createSurfaceForWindow( native_instance: *const gpu.NativeInstance, window: glfw.Window, comptime glfw_options: glfw.BackendOptions, ) gpu.Surface { const glfw_native = glfw.Native(glfw_options); const descriptor = if (glfw_options.win32) gpu.Surface.Descriptor{ .windows_hwnd = .{ .label = "basic surface", .hinstance = std.os.windows.kernel32.GetModuleHandleW(null).?, .hwnd = glfw_native.getWin32Window(window), }, } else if (glfw_options.x11) gpu.Surface.Descriptor{ .xlib = .{ .label = "basic surface", .display = glfw_native.getX11Display(), .window = glfw_native.getX11Window(window), }, } else if (glfw_options.cocoa) blk: { const ns_window = glfw_native.getCocoaWindow(window); const ns_view = msgSend(ns_window, "contentView", .{}, *anyopaque); // [nsWindow contentView] // Create a CAMetalLayer that covers the whole window that will be passed to CreateSurface. msgSend(ns_view, "setWantsLayer:", .{true}, void); // [view setWantsLayer:YES] const layer = msgSend(objc.objc_getClass("CAMetalLayer"), "layer", .{}, ?*anyopaque); // [CAMetalLayer layer] if (layer == null) @panic("failed to create Metal layer"); msgSend(ns_view, "setLayer:", .{layer.?}, void); // [view setLayer:layer] // Use retina if the window was created with retina support. const scale_factor = msgSend(ns_window, "backingScaleFactor", .{}, f64); // [ns_window backingScaleFactor] msgSend(layer.?, "setContentsScale:", .{scale_factor}, void); // [layer setContentsScale:scale_factor] break :blk gpu.Surface.Descriptor{ .metal_layer = .{ .label = "basic surface", .layer = layer.?, }, }; } else if (glfw_options.wayland) { @panic("Dawn does not yet have Wayland support, see https://bugs.chromium.org/p/dawn/issues/detail?id=1246&q=surface&can=2"); } else unreachable; return native_instance.createSurface(&descriptor); } // Borrowed from https://github.com/hazeycode/zig-objcrt pub fn msgSend(obj: anytype, sel_name: [:0]const u8, args: anytype, comptime ReturnType: type) ReturnType { const args_meta = @typeInfo(@TypeOf(args)).Struct.fields; const FnType = switch (args_meta.len) { 0 => fn (@TypeOf(obj), objc.SEL) callconv(.C) ReturnType, 1 => fn (@TypeOf(obj), objc.SEL, args_meta[0].field_type) callconv(.C) ReturnType, 2 => fn (@TypeOf(obj), objc.SEL, args_meta[0].field_type, args_meta[1].field_type) callconv(.C) ReturnType, 3 => fn (@TypeOf(obj), objc.SEL, args_meta[0].field_type, args_meta[1].field_type, args_meta[2].field_type) callconv(.C) ReturnType, 4 => fn (@TypeOf(obj), objc.SEL, args_meta[0].field_type, args_meta[1].field_type, args_meta[2].field_type, args_meta[3].field_type) callconv(.C) ReturnType, else => @compileError("Unsupported number of args"), }; // NOTE: func is a var because making it const causes a compile error which I believe is a compiler bug var func = @ptrCast(FnType, objc.objc_msgSend); const sel = objc.sel_getUid(sel_name); return @call(.{}, func, .{ obj, sel } ++ args); }
gpu/examples/sample_utils.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const col = @import("color.zig"); const Color = col.Color; const IndexedBitmap = @import("IndexedBitmap.zig"); width: u32, height: u32, pixels: []u8, const ColorBitmap = @This(); pub fn init(allocator: Allocator, width: u32, height: u32) !ColorBitmap { var self = ColorBitmap{ .width = width, .height = height, .pixels = undefined, }; self.pixels = try allocator.alloc(u8, self.width * self.height * @sizeOf(Color)); return self; } pub fn deinit(self: ColorBitmap, allocator: Allocator) void { allocator.free(self.pixels); } pub fn clone(self: ColorBitmap, allocator: Allocator) !ColorBitmap { return ColorBitmap{ .width = self.width, .height = self.height, .pixels = try allocator.dupe(u8, self.pixels), }; } pub fn eql(self: ColorBitmap, bitmap: ColorBitmap) bool { return self.width == bitmap.width and self.width == bitmap.width and std.mem.eql(u8, self.pixels, bitmap.pixels); } pub fn canLosslesslyConvertToIndexed(self: ColorBitmap, allocator: Allocator, colormap: []const u8) !bool { var color: [4]u8 = undefined; var color_set = std.AutoHashMap(@TypeOf(color), void).init(allocator); defer color_set.deinit(); var i: usize = 0; while (i < 256) : (i += 1) { std.mem.copy(u8, &color, colormap[4 * i ..][0..4]); try color_set.put(color, {}); } const pixel_count = self.width * self.height; i = 0; while (i < pixel_count) : (i += 1) { std.mem.copy(u8, &color, self.pixels[4 * i ..][0..4]); if (!color_set.contains(color)) return false; } return true; } pub fn convertToIndexed(self: ColorBitmap, allocator: Allocator, colormap: []const u8) !IndexedBitmap { const indexed_bitmap = try IndexedBitmap.init(allocator, self.width, self.height); const pixel_count = indexed_bitmap.width * indexed_bitmap.height; var i: usize = 0; while (i < pixel_count) : (i += 1) { indexed_bitmap.indices[i] = @truncate(u8, col.findNearest(colormap, self.pixels[4 * i ..])); } return indexed_bitmap; } pub fn setPixel(self: ColorBitmap, x: i32, y: i32, color: Color) bool { if (x >= 0 and y >= 0) { const ux = @intCast(u32, x); const uy = @intCast(u32, y); if (ux < self.width and uy < self.height) { self.setPixelUnchecked(ux, uy, color); return true; } } return false; } pub fn blendPixel(self: ColorBitmap, x: i32, y: i32, color: Color) bool { if (self.getPixel(x, y)) |dst| { const blended = col.blend(color[0..], dst[0..]); self.setPixelUnchecked(@intCast(u32, x), @intCast(u32, y), blended); return true; } return false; } pub fn setPixelUnchecked(self: ColorBitmap, x: u32, y: u32, color: Color) void { std.debug.assert(x < self.width); std.mem.copy(u8, self.pixels[4 * (y * self.width + x) ..][0..4], &color); } pub fn getPixel(self: ColorBitmap, x: i32, y: i32) ?Color { if (x >= 0 and y >= 0) { const ux = @intCast(u32, x); const uy = @intCast(u32, y); if (ux < self.width and uy < self.height) { return self.getPixelUnchecked(ux, uy); } } return null; } pub fn getPixelUnchecked(self: ColorBitmap, x: u32, y: u32) Color { std.debug.assert(x < self.width); const c = self.pixels[4 * (y * self.width + x) ..]; return Color{ c[0], c[1], c[2], c[3] }; } pub fn copyPixelUnchecked(self: ColorBitmap, dst: ColorBitmap, x: u32, y: u32) void { const src_color = self.getPixelUnchecked(x, y); dst.setPixelUnchecked(x, y, src_color); } pub fn drawLine(self: ColorBitmap, x0: i32, y0: i32, x1: i32, y1: i32, color: Color, skip_first: bool) void { const dx = std.math.absInt(x1 - x0) catch unreachable; const sx: i32 = if (x0 < x1) 1 else -1; const dy = -(std.math.absInt(y1 - y0) catch unreachable); const sy: i32 = if (y0 < y1) 1 else -1; var err = dx + dy; if (!skip_first) { _ = self.setPixel(x0, y0, color); } var x = x0; var y = y0; while (x != x1 or y != y1) { const e2 = 2 * err; if (e2 >= dy) { err += dy; x += sx; } if (e2 <= dx) { err += dx; y += sy; } _ = self.setPixel(x, y, color); } } pub fn blendLine(self: ColorBitmap, x0: i32, y0: i32, x1: i32, y1: i32, color: Color, skip_first: bool) void { const dx = std.math.absInt(x1 - x0) catch unreachable; const sx: i32 = if (x0 < x1) 1 else -1; const dy = -(std.math.absInt(y1 - y0) catch unreachable); const sy: i32 = if (y0 < y1) 1 else -1; var err = dx + dy; if (!skip_first) { _ = self.blendPixel(x0, y0, color); } var x = x0; var y = y0; while (x != x1 or y != y1) { const e2 = 2 * err; if (e2 >= dy) { err += dy; x += sx; } if (e2 <= dx) { err += dx; y += sy; } _ = self.blendPixel(x, y, color); } } pub fn copyLine(self: ColorBitmap, dst: ColorBitmap, x0: i32, y0: i32, x1: i32, y1: i32) void { const dx = std.math.absInt(x1 - x0) catch unreachable; const sx: i32 = if (x0 < x1) 1 else -1; const dy = -(std.math.absInt(y1 - y0) catch unreachable); const sy: i32 = if (y0 < y1) 1 else -1; var err = dx + dy; var x = x0; var y = y0; while (true) { if (self.getPixel(x, y)) |src_color| { dst.setPixelUnchecked(@intCast(u32, x), @intCast(u32, y), src_color); } if (x == x1 and y == y1) break; const e2 = 2 * err; if (e2 >= dy) { err += dy; x += sx; } if (e2 <= dx) { err += dx; y += sy; } } } pub fn clear(self: ColorBitmap) void { std.mem.set(u8, self.pixels, 0); } pub fn fill(self: ColorBitmap, color: Color) void { var i: usize = 0; while (i < self.pixels.len) : (i += 1) { self.pixels[i] = color[i % 4]; } } pub fn floodFill(self: *ColorBitmap, allocator: Allocator, x: i32, y: i32, color: Color) !void { const old_color = self.getPixel(x, y) orelse return; if (col.eql(old_color, color)) return; const start_coords = .{ .x = @intCast(u32, x), .y = @intCast(u32, y) }; self.setPixelUnchecked(start_coords.x, start_coords.y, color); var stack = std.ArrayList(struct { x: u32, y: u32 }).init(allocator); try stack.ensureTotalCapacity(self.width * self.height / 2); defer stack.deinit(); try stack.append(start_coords); while (stack.items.len > 0) { const coords = stack.pop(); if (coords.y > 0) { const new_coords = .{ .x = coords.x, .y = coords.y - 1 }; if (col.eql(self.getPixelUnchecked(new_coords.x, new_coords.y), old_color)) { self.setPixelUnchecked(new_coords.x, new_coords.y, color); stack.appendAssumeCapacity(new_coords); } } if (coords.y < self.height - 1) { const new_coords = .{ .x = coords.x, .y = coords.y + 1 }; if (col.eql(self.getPixelUnchecked(new_coords.x, new_coords.y), old_color)) { self.setPixelUnchecked(new_coords.x, new_coords.y, color); stack.appendAssumeCapacity(new_coords); } } if (coords.x > 0) { const new_coords = .{ .x = coords.x - 1, .y = coords.y }; if (col.eql(self.getPixelUnchecked(new_coords.x, new_coords.y), old_color)) { self.setPixelUnchecked(new_coords.x, new_coords.y, color); stack.appendAssumeCapacity(new_coords); } } if (coords.x < self.width - 1) { const new_coords = .{ .x = coords.x + 1, .y = coords.y }; if (col.eql(self.getPixelUnchecked(new_coords.x, new_coords.y), old_color)) { self.setPixelUnchecked(new_coords.x, new_coords.y, color); stack.appendAssumeCapacity(new_coords); } } } } pub fn mirrorHorizontally(self: ColorBitmap) void { var y: u32 = 0; while (y < self.height) : (y += 1) { var x0: u32 = 0; var x1: u32 = self.width - 1; while (x0 < x1) { const color0 = self.getPixelUnchecked(x0, y); const color1 = self.getPixelUnchecked(x1, y); self.setPixelUnchecked(x0, y, color1); self.setPixelUnchecked(x1, y, color0); x0 += 1; x1 -= 1; } } } pub fn mirrorVertically(self: ColorBitmap) void { var y0: u32 = 0; var y1: u32 = self.height - 1; while (y0 < y1) { var x: u32 = 0; while (x < self.width) : (x += 1) { const color0 = self.getPixelUnchecked(x, y0); const color1 = self.getPixelUnchecked(x, y1); self.setPixelUnchecked(x, y0, color1); self.setPixelUnchecked(x, y1, color0); } y0 += 1; y1 -= 1; } } pub fn rotate(self: *ColorBitmap, allocator: Allocator, clockwise: bool) !void { const tmp_bitmap = try self.clone(allocator); defer tmp_bitmap.deinit(allocator); std.mem.swap(u32, &self.width, &self.height); var y: u32 = 0; while (y < self.width) : (y += 1) { var x: u32 = 0; while (x < self.height) : (x += 1) { const color = tmp_bitmap.getPixelUnchecked(x, y); if (clockwise) { self.setPixelUnchecked(self.width - 1 - y, x, color); } else { self.setPixelUnchecked(y, self.height - 1 - x, color); } } } } test "rotate" { const initial = ColorBitmap{ .width = 2, .height = 3, .pixels = try testing.allocator.dupe(u8, &[_]u8{ 0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14, 0x21, 0x22, 0x23, 0x24, 0x31, 0x32, 0x33, 0x34, 0x41, 0x42, 0x43, 0x44, 0x51, 0x52, 0x53, 0x54, }), }; defer initial.deinit(testing.allocator); const rotated = ColorBitmap{ .width = 3, .height = 2, .pixels = try testing.allocator.dupe(u8, &[_]u8{ 0x41, 0x42, 0x43, 0x44, 0x21, 0x22, 0x23, 0x24, 0x01, 0x02, 0x03, 0x04, 0x51, 0x52, 0x53, 0x54, 0x31, 0x32, 0x33, 0x34, 0x11, 0x12, 0x13, 0x14, }), }; defer rotated.deinit(testing.allocator); var bmp = try initial.clone(testing.allocator); defer bmp.deinit(testing.allocator); try bmp.rotate(testing.allocator, true); try testing.expect(bmp.eql(rotated)); try bmp.rotate(testing.allocator, false); try testing.expect(bmp.eql(initial)); }
src/ColorBitmap.zig
const std = @import("std"); const upaya = @import("upaya"); const data = @import("map.zig"); const Map = data.Map; const Rule = data.Rule; const RuleTile = data.RuleTile; const AppState = @import("tilescript.zig").AppState; /// runs the input map directly from Map through all the pre-processing rules and copies the data into state pub fn generateProcessedMap(state: *AppState) void { @memcpy(state.processed_map_data.ptr, state.map.data.ptr, state.map.data.len); if (state.map.pre_rulesets.items.len == 0) { return; } // we need an extra buffer so that we can write into it for each iteration so our rules dont go hog-crazy as we iterate var buffer = upaya.mem.tmp_allocator.alloc(u8, state.map.data.len) catch unreachable; std.mem.set(u8, buffer, 0); for (state.map.pre_rulesets.items) |ruleset| { state.generateRandomData(ruleset.seed); // we need at least 1 iteration, then however many repeats were requested var max_iters: usize = 1 + ruleset.repeat; var iter: usize = 0; while (iter < max_iters) : (iter += 1) { var y: usize = 0; while (y < state.map.h) : (y += 1) { var x: usize = 0; while (x < state.map.w) : (x += 1) { buffer[x + y * state.map.w] = transformTileWithRuleSet(state, state.processed_map_data, ruleset.rules.items, true, x, y); } } // if something changed copy the buffer and go for another round else we bail out if (!std.mem.eql(u8, buffer, state.processed_map_data)) { @memcpy(state.processed_map_data.ptr, buffer.ptr, buffer.len); } else { iter = max_iters; } } } } pub fn generateOutputMap(state: *AppState) void { state.generateRandomData(state.map.ruleset.seed); var y: usize = 0; while (y < state.map.h) : (y += 1) { var x: usize = 0; while (x < state.map.w) : (x += 1) { state.final_map_data[x + y * state.map.w] = transformTileWithRuleSet(state, state.processed_map_data, state.map.ruleset.rules.items, false, x, y); } } } pub fn transformTileWithRuleSet(state: *AppState, tile_source: []u8, rules: []Rule, is_pre_ruleset: bool, x: usize, y: usize) u8 { var rule_passed = false; for (rules) |*rule| brk: { if (rule.result_tiles.len == 0) continue; // at least one rule must pass to have a result for (rule.rule_tiles) |rule_tile, i| { if (rule_tile.state == .none) continue; const x_offset = @intCast(i32, @mod(i, 5)) - 2; const y_offset = @intCast(i32, @divTrunc(i, 5)) - 2; // stay in bounds! We could be looking for a tile 2 away from x,y in any direction const actual_x = @intCast(i32, x) + x_offset; const actual_y = @intCast(i32, y) + y_offset; const processed_tile = if (actual_x < 0 or actual_y < 0 or actual_x >= state.map.w or actual_y >= state.map.h) 0 else blk: { const index = @intCast(usize, actual_x) + @intCast(usize, actual_y) * state.map.w; break :blk tile_source[index]; }; // if any rule fails, we are done with this RuleSet if (!rule_tile.passes(processed_tile)) { break :brk; } rule_passed = true; } // a Rule passed. we use the chance to decide if we will return a tile const random = state.random_map_data[x + y * state.map.w]; const chance = random.float < @intToFloat(f32, rule.chance) / 100; if (rule_passed and chance) { return @intCast(u8, rule.resultTile(random.int) + 1); } } if (is_pre_ruleset) { return tile_source[x + y * state.map.w]; } return 0; }
tilescript/rule_processor.zig
const VTE = @import("vte"); const c = VTE.c; const gtk = VTE.gtk; const vte = VTE.vte; const std = @import("std"); const allocator = std.heap.page_allocator; const Closures = @import("gui.zig").Closures; const k = @import("keys.zig"); const Accel = k.Accel; const Keys = k.Keys; pub const Menu = struct { new_tab: gtk.MenuItem, split_view: gtk.MenuItem, rotate_view: gtk.MenuItem, copy: gtk.MenuItem, paste: gtk.MenuItem, preferences: gtk.MenuItem, close_tab: gtk.MenuItem, quit: gtk.MenuItem, const Self = @This(); pub fn init(builder: gtk.Builder) Self { return Self{ .new_tab = builder.get_widget("new_tab").?.to_menu_item().?, .split_view = builder.get_widget("split_view").?.to_menu_item().?, .rotate_view = builder.get_widget("rotate_view").?.to_menu_item().?, .copy = builder.get_widget("copy").?.to_menu_item().?, .paste = builder.get_widget("paste").?.to_menu_item().?, .preferences = builder.get_widget("preferences").?.to_menu_item().?, .close_tab = builder.get_widget("close_tab").?.to_menu_item().?, .quit = builder.get_widget("quit_app").?.to_menu_item().?, }; } pub fn setAccels(self: Self, accel_group: *c.GtkAccelGroup, keys: Keys) void { const newTab = c.g_cclosure_new(Closures.newTab, null, null); const splitView = c.g_cclosure_new(Closures.splitView, null, null); const rotateView = c.g_cclosure_new(Closures.rotateView, null, null); const copy = c.g_cclosure_new(Closures.copy, null, null); const paste = c.g_cclosure_new(Closures.paste, null, null); const quit = c.g_cclosure_new(Closures.quit, null, null); var accel: Accel = undefined; if (self.new_tab.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.new_tab); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, newTab); } if (self.split_view.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.views.split_view); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, splitView); } if (self.rotate_view.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.views.rotate_view); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, rotateView); } if (self.copy.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.actions.copy); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, copy); } if (self.paste.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.actions.paste); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, paste); } if (self.quit.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.actions.quit); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, quit); } } }; pub const Nav = struct { prev_pane: gtk.MenuItem, next_pane: gtk.MenuItem, prev_tab: gtk.MenuItem, next_tab: gtk.MenuItem, tab1: gtk.MenuItem, tab2: gtk.MenuItem, tab3: gtk.MenuItem, tab4: gtk.MenuItem, tab5: gtk.MenuItem, tab6: gtk.MenuItem, tab7: gtk.MenuItem, tab8: gtk.MenuItem, tab9: gtk.MenuItem, const Self = @This(); pub fn init(builder: gtk.Builder) Self { return Self{ .prev_pane = builder.get_widget("prev_pane").?.to_menu_item().?, .next_pane = builder.get_widget("next_pane").?.to_menu_item().?, .prev_tab = builder.get_widget("prev_tab").?.to_menu_item().?, .next_tab = builder.get_widget("next_tab").?.to_menu_item().?, .tab1 = builder.get_widget("tab_1").?.to_menu_item().?, .tab2 = builder.get_widget("tab_2").?.to_menu_item().?, .tab3 = builder.get_widget("tab_3").?.to_menu_item().?, .tab4 = builder.get_widget("tab_4").?.to_menu_item().?, .tab5 = builder.get_widget("tab_5").?.to_menu_item().?, .tab6 = builder.get_widget("tab_6").?.to_menu_item().?, .tab7 = builder.get_widget("tab_7").?.to_menu_item().?, .tab8 = builder.get_widget("tab_8").?.to_menu_item().?, .tab9 = builder.get_widget("tab_9").?.to_menu_item().?, }; } pub fn setAccels(self: Self, accel_group: *c.GtkAccelGroup, keys: Keys) void { const tab1 = c.g_cclosure_new(Closures.tab1, null, null); const tab2 = c.g_cclosure_new(Closures.tab2, null, null); const tab3 = c.g_cclosure_new(Closures.tab3, null, null); const tab4 = c.g_cclosure_new(Closures.tab4, null, null); const tab5 = c.g_cclosure_new(Closures.tab5, null, null); const tab6 = c.g_cclosure_new(Closures.tab6, null, null); const tab7 = c.g_cclosure_new(Closures.tab7, null, null); const tab8 = c.g_cclosure_new(Closures.tab8, null, null); const tab9 = c.g_cclosure_new(Closures.tab9, null, null); const prevPane = c.g_cclosure_new(Closures.prevPane, null, null); const nextPane = c.g_cclosure_new(Closures.nextPane, null, null); const prevTab = c.g_cclosure_new(Closures.prevTab, null, null); const nextTab = c.g_cclosure_new(Closures.nextTab, null, null); var accel: Accel = undefined; if (self.tab1.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab1); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab1); } if (self.tab2.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab2); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab2); } if (self.tab3.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab3); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab3); } if (self.tab4.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab4); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab4); } if (self.tab5.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab5); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab5); } if (self.tab6.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab6); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab6); } if (self.tab7.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab7); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab7); } if (self.tab8.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab8); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab8); } if (self.tab9.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.tab9); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, tab9); } if (self.prev_pane.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.views.prev_view); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, prevPane); } if (self.next_pane.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.views.next_view); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, nextPane); } if (self.prev_tab.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.prev_tab); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, prevTab); } if (self.next_tab.get_accel_path(allocator)) |p| { defer allocator.free(p); accel = Accel.parse(keys.tabs.next_tab); c.gtk_accel_map_add_entry(p, accel.key, accel.mods); c.gtk_accel_group_connect_by_path(accel_group, p, nextTab); } } };
src/menus.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log.scoped(.reloc); const macho = std.macho; const math = std.math; const mem = std.mem; const meta = std.meta; const aarch64 = @import("reloc/aarch64.zig"); const x86_64 = @import("reloc/x86_64.zig"); const Allocator = mem.Allocator; const Symbol = @import("Symbol.zig"); pub const Relocation = struct { @"type": Type, code: []u8, offset: u32, target: Target, pub fn cast(base: *Relocation, comptime T: type) ?*T { if (base.@"type" != T.base_type) return null; return @fieldParentPtr(T, "base", base); } pub const ResolveArgs = struct { source_addr: u64, target_addr: u64, subtractor: ?u64 = null, source_sect_addr: ?u64 = null, }; pub fn resolve(base: *Relocation, args: ResolveArgs) !void { log.debug("{s}", .{base.@"type"}); log.debug(" | offset 0x{x}", .{base.offset}); log.debug(" | source address 0x{x}", .{args.source_addr}); log.debug(" | target address 0x{x}", .{args.target_addr}); if (args.subtractor) |sub| log.debug(" | subtractor address 0x{x}", .{sub}); if (args.source_sect_addr) |addr| log.debug(" | source section address 0x{x}", .{addr}); return switch (base.@"type") { .unsigned => @fieldParentPtr(Unsigned, "base", base).resolve(args), .branch_aarch64 => @fieldParentPtr(aarch64.Branch, "base", base).resolve(args), .page => @fieldParentPtr(aarch64.Page, "base", base).resolve(args), .page_off => @fieldParentPtr(aarch64.PageOff, "base", base).resolve(args), .got_page => @fieldParentPtr(aarch64.GotPage, "base", base).resolve(args), .got_page_off => @fieldParentPtr(aarch64.GotPageOff, "base", base).resolve(args), .tlvp_page => @fieldParentPtr(aarch64.TlvpPage, "base", base).resolve(args), .tlvp_page_off => @fieldParentPtr(aarch64.TlvpPageOff, "base", base).resolve(args), .branch_x86_64 => @fieldParentPtr(x86_64.Branch, "base", base).resolve(args), .signed => @fieldParentPtr(x86_64.Signed, "base", base).resolve(args), .got_load => @fieldParentPtr(x86_64.GotLoad, "base", base).resolve(args), .got => @fieldParentPtr(x86_64.Got, "base", base).resolve(args), .tlv => @fieldParentPtr(x86_64.Tlv, "base", base).resolve(args), }; } pub const Type = enum { branch_aarch64, unsigned, page, page_off, got_page, got_page_off, tlvp_page, tlvp_page_off, branch_x86_64, signed, got_load, got, tlv, }; pub const Target = union(enum) { symbol: *Symbol, section: u16, pub fn from_reloc(reloc: macho.relocation_info, symbols: []*Symbol) Target { return if (reloc.r_extern == 1) .{ .symbol = symbols[reloc.r_symbolnum], } else .{ .section = @intCast(u16, reloc.r_symbolnum - 1), }; } }; }; pub const Unsigned = struct { base: Relocation, subtractor: ?Relocation.Target = null, /// Addend embedded directly in the relocation slot addend: i64, /// Extracted from r_length: /// => 3 implies true /// => 2 implies false /// => * is unreachable is_64bit: bool, pub const base_type: Relocation.Type = .unsigned; pub fn resolve(unsigned: Unsigned, args: Relocation.ResolveArgs) !void { const addend = if (unsigned.base.target == .section) unsigned.addend - @intCast(i64, args.source_sect_addr.?) else unsigned.addend; const result = if (args.subtractor) |subtractor| @intCast(i64, args.target_addr) - @intCast(i64, subtractor) + addend else @intCast(i64, args.target_addr) + addend; log.debug(" | calculated addend 0x{x}", .{addend}); log.debug(" | calculated unsigned value 0x{x}", .{result}); if (unsigned.is_64bit) { mem.writeIntLittle( u64, unsigned.base.code[0..8], @bitCast(u64, result), ); } else { mem.writeIntLittle( u32, unsigned.base.code[0..4], @truncate(u32, @bitCast(u64, result)), ); } } }; pub fn parse( allocator: *Allocator, arch: std.Target.Cpu.Arch, code: []u8, relocs: []const macho.relocation_info, symbols: []*Symbol, ) ![]*Relocation { var it = RelocIterator{ .buffer = relocs, }; switch (arch) { .aarch64 => { var parser = aarch64.Parser{ .allocator = allocator, .it = &it, .code = code, .parsed = std.ArrayList(*Relocation).init(allocator), .symbols = symbols, }; defer parser.deinit(); try parser.parse(); return parser.parsed.toOwnedSlice(); }, .x86_64 => { var parser = x86_64.Parser{ .allocator = allocator, .it = &it, .code = code, .parsed = std.ArrayList(*Relocation).init(allocator), .symbols = symbols, }; defer parser.deinit(); try parser.parse(); return parser.parsed.toOwnedSlice(); }, else => unreachable, } } pub const RelocIterator = struct { buffer: []const macho.relocation_info, index: i64 = -1, pub fn next(self: *RelocIterator) ?macho.relocation_info { self.index += 1; if (self.index < self.buffer.len) { const reloc = self.buffer[@intCast(u64, self.index)]; log.debug("relocation", .{}); log.debug(" | type = {}", .{reloc.r_type}); log.debug(" | offset = {}", .{reloc.r_address}); log.debug(" | PC = {}", .{reloc.r_pcrel == 1}); log.debug(" | length = {}", .{reloc.r_length}); log.debug(" | symbolnum = {}", .{reloc.r_symbolnum}); log.debug(" | extern = {}", .{reloc.r_extern == 1}); return reloc; } return null; } pub fn peek(self: RelocIterator) macho.relocation_info { assert(self.index + 1 < self.buffer.len); return self.buffer[@intCast(u64, self.index + 1)]; } };
src/link/MachO/reloc.zig
const std = @import("std"); const wlr = @cImport({ @cDefine("_POSIX_C_SOURCE", "200112L"); @cDefine("WLR_USE_UNSTABLE", {}); @cInclude("linux/input-event-codes.h"); @cInclude("unistd.h"); @cInclude("wayland-server-core.h"); @cInclude("wlr/backend.h"); @cInclude("wlr/backend/libinput.h"); @cInclude("wlr/render/allocator.h"); @cInclude("wlr/render/wlr_renderer.h"); @cInclude("wlr/types/wlr_cursor.h"); @cInclude("wlr/types/wlr_compositor.h"); @cInclude("wlr/types/wlr_data_control_v1.h"); @cInclude("wlr/types/wlr_data_device.h"); @cInclude("wlr/types/wlr_export_dmabuf_v1.h"); @cInclude("wlr/types/wlr_gamma_control_v1.h"); @cInclude("wlr/types/wlr_idle.h"); @cInclude("wlr/types/wlr_input_device.h"); @cInclude("wlr/types/wlr_input_inhibitor.h"); @cInclude("wlr/types/wlr_keyboard.h"); @cInclude("wlr/types/wlr_layer_shell_v1.h"); @cInclude("wlr/types/wlr_matrix.h"); @cInclude("wlr/types/wlr_output.h"); @cInclude("wlr/types/wlr_output_damage.h"); @cInclude("wlr/types/wlr_output_layout.h"); @cInclude("wlr/types/wlr_output_management_v1.h"); @cInclude("wlr/types/wlr_pointer.h"); @cInclude("wlr/types/wlr_presentation_time.h"); @cInclude("wlr/types/wlr_primary_selection.h"); @cInclude("wlr/types/wlr_primary_selection_v1.h"); @cInclude("wlr/types/wlr_seat.h"); @cInclude("wlr/types/wlr_server_decoration.h"); @cInclude("wlr/types/wlr_screencopy_v1.h"); @cInclude("wlr/types/wlr_viewporter.h"); @cInclude("wlr/types/wlr_xcursor_manager.h"); @cInclude("wlr/types/wlr_xdg_shell.h"); @cInclude("wlr/types/wlr_xdg_decoration_v1.h"); @cInclude("wlr/types/wlr_xdg_output_v1.h"); @cInclude("wlr/util/log.h"); @cInclude("wlr/util/region.h"); @cInclude("wlr/xwayland.h"); @cInclude("X11/Xlib.h"); @cInclude("xkbcommon/xkbcommon.h"); }); pub fn main() !void { std.log.info("Starting Byway", .{}); var server: Server = undefined; try server.init(); defer server.deinit(); try server.start(); std.log.info("Exiting Byway", .{}); } const Surface = struct { fn create(server: *Server, typed_surface: anytype, ancestor: ?*Surface) !?*Surface { if (@TypeOf(typed_surface) == *wlr.wlr_xdg_surface and typed_surface.role == wlr.WLR_XDG_SURFACE_ROLE_POPUP and ancestor == null) { return null; } var surface = try alloc.create(Surface); try surface.init(typed_surface, server, ancestor); return surface; } fn init( self: *Surface, typed_surface: anytype, server: *Server, ancestor: ?*Surface, ) !void { self.server = server; self.wlr_surface = null; self.mapped = false; self.list = null; self.node.data = self; self.is_requested_fullscreen = false; self.has_border = false; self.ancestor = ancestor; self.output_box = .{ .x = 0, .y = 0, .width = 0, .height = 0 }; self.workspace = 0; self.is_actual_fullscreen = false; self.borders = .{ .{ .x = 0, .y = 0, .width = 0, .height = 0 }, .{ .x = 0, .y = 0, .width = 0, .height = 0 }, .{ .x = 0, .y = 0, .width = 0, .height = 0 }, .{ .x = 0, .y = 0, .width = 0, .height = 0 }, }; Signal.connect(void, self, "map", Surface.onMap, &typed_surface.events.map); Signal.connect(void, self, "unmap", Surface.onUnmap, &typed_surface.events.unmap); Signal.connect(void, self, "destroy", Surface.onDestroy, &typed_surface.events.destroy); switch (@TypeOf(typed_surface)) { *wlr.wlr_xdg_surface => { self.typed_surface = SurfaceType{ .xdg = typed_surface }; Signal.connect( *wlr.wlr_xdg_popup, self, "popup", Surface.onNewPopup, &typed_surface.events.new_popup, ); switch (typed_surface.role) { wlr.WLR_XDG_SURFACE_ROLE_TOPLEVEL => { wlr.wlr_xdg_surface_ping(typed_surface); self.list = &server.toplevels; self.has_border = true; Signal.connect( void, self, "request_fullscreen", Surface.onRequestFullscreen, &@ptrCast( *wlr.wlr_xdg_toplevel, @field(typed_surface, wlr_xdg_surface_union).toplevel, ).events.request_fullscreen, ); }, else => {}, } }, *wlr.wlr_xwayland_surface => { self.typed_surface = SurfaceType{ .xwayland = typed_surface }; if (typed_surface.override_redirect) { self.list = &server.unmanaged_toplevels; } else { self.has_border = true; self.list = &server.toplevels; } Signal.connect( void, self, "request_fullscreen", Surface.onRequestFullscreen, &typed_surface.events.request_fullscreen, ); Signal.connect( void, self, "activate", Surface.onActivate, &typed_surface.events.request_activate, ); Signal.connect( *wlr.wlr_xwayland_surface_configure_event, self, "configure", Surface.onConfigure, &typed_surface.events.request_configure, ); }, *wlr.wlr_layer_surface_v1 => { self.typed_surface = SurfaceType{ .layer = typed_surface }; Signal.connect( *wlr.wlr_xdg_popup, self, "popup", Surface.onNewPopup, &typed_surface.events.new_popup, ); if (server.outputAtCursor()) |output| { if (typed_surface.output == null) { typed_surface.output = output.wlr_output; } } if (Output.fromWlrOutput(typed_surface.output)) |output| { self.layer = typed_surface.pending.layer; output.layers[self.layer].prepend(&self.node); output.arrangeLayers(); } }, *wlr.wlr_subsurface => { self.typed_surface = SurfaceType{ .subsurface = typed_surface }; }, *wlr.wlr_drag_icon => { self.typed_surface = SurfaceType{ .drag_icon = typed_surface }; }, else => { std.log.err("unknown surface {s} {d}", .{ @TypeOf(typed_surface), typed_surface }); }, } } fn onCommit(self: *Surface, _: void) !void { switch (self.typed_surface) { .xdg => |xdg| { if (self.pending_serial > 0 and xdg.current.configure_serial >= self.pending_serial) { self.pending_serial = 0; self.server.damageAllOutputs(); } }, .layer => |layer_surface| { if (Output.fromWlrOutput(layer_surface.output)) |output| { if (layer_surface.current.committed != 0 or self.mapped != layer_surface.mapped) { self.mapped = layer_surface.mapped; if (self.layer != layer_surface.current.layer) { output.layers[self.layer].remove(&self.node); output.layers[layer_surface.current.layer].prepend( &self.node, ); self.layer = layer_surface.current.layer; } output.arrangeLayers(); } } }, else => {}, } self.updateBorders(); self.damage(if (self.server.config.damage_tracking == .full) false else true); } fn shouldFocus(self: *Surface) bool { return switch (self.typed_surface) { .xwayland => |xwayland| !xwayland.override_redirect or wlr.wlr_xwayland_or_surface_wants_focus(xwayland), .layer => self.layer != wlr.ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND and self.layer != wlr.ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM, else => true, }; } fn onMap(self: *Surface, _: void) !void { self.mapped = true; self.initWlrSurface(); if (self.has_border) self.place(); switch (self.typed_surface) { .xwayland => |xwayland| { self.output_box.x = xwayland.x; self.output_box.y = xwayland.y; }, else => {}, } if (self.list) |list| list.prepend(&self.node); self.setKeyboardFocus(); self.updateOutputs(); self.server.damageAllOutputs(); } fn onUnmap(self: *Surface, _: void) !void { if (!self.mapped) return; self.mapped = false; wlr.wl_list_remove(&self.commit.link); switch (self.typed_surface) { .xdg, .subsurface => { wlr.wl_list_remove(&self.subsurface.link); }, else => {}, } self.server.damageAllOutputs(); self.wlr_surface = null; if (self.list) |list| { list.remove(&self.node); } self.server.processCursorMotion(0); } fn onDestroy(self: *Surface, _: void) !void { wlr.wl_list_remove(&self.map.link); wlr.wl_list_remove(&self.unmap.link); if (self.mapped) { self.server.damageAllOutputs(); } wlr.wl_list_remove(&self.destroy.link); if (self.list) |_| { wlr.wl_list_remove(&self.request_fullscreen.link); switch (self.typed_surface) { .xwayland => |xwayland| { if (!xwayland.override_redirect) { wlr.wl_list_remove(&self.activate.link); wlr.wl_list_remove(&self.configure.link); } }, else => {}, } } switch (self.typed_surface) { .layer => |layer_surface| { if (Output.fromWlrOutput(layer_surface.output)) |output| { output.arrangeLayers(); output.layers[self.layer].remove(&self.node); layer_surface.output = null; } }, else => {}, } alloc.destroy(self); } fn onActivate(self: *Surface, _: void) !void { switch (self.typed_surface) { .xwayland => |xwayland| { wlr.wlr_xwayland_surface_activate(xwayland, true); }, else => { std.log.err("unexpected activate", .{}); }, } self.server.damageAllOutputs(); } fn onConfigure( self: *Surface, event: *wlr.wlr_xwayland_surface_configure_event, ) !void { switch (self.typed_surface) { .xwayland => |xwayland| { self.updateBorders(); wlr.wlr_xwayland_surface_configure( xwayland, event.x, event.y, event.width, event.height, ); }, else => { std.log.err("unexpected configure", .{}); }, } self.server.damageAllOutputs(); } fn onNewPopup(self: *Surface, wlr_popup: *wlr.wlr_xdg_popup) !void { _ = try Surface.create( self.server, @ptrCast(*wlr.wlr_xdg_surface, wlr_popup.base), if (self.has_border) self else if (self.ancestor) |ancestor| ancestor else self, ); } fn onNewSubsurface(self: *Surface, wlr_subsurface: *wlr.wlr_subsurface) !void { _ = try Surface.create(self.server, wlr_subsurface, if (self.has_border) self else self.ancestor); } fn onRequestFullscreen(self: *Surface, _: void) !void { self.is_requested_fullscreen = !self.is_requested_fullscreen; switch (self.typed_surface) { .xdg => |xdg| { _ = wlr.wlr_xdg_toplevel_set_fullscreen(xdg, self.is_requested_fullscreen); }, .xwayland => |xwayland| { wlr.wlr_xwayland_surface_set_fullscreen(xwayland, self.is_requested_fullscreen); }, else => {}, } } fn initWlrSurface(self: *Surface) void { if (self.wlr_surface != null) return; self.wlr_surface = switch (self.typed_surface) { .xdg => |xdg| xdg.surface, .xwayland => |xwayland| xwayland.surface, .layer => |layer_surface| layer_surface.surface, .subsurface => |subsurface| subsurface.surface, .drag_icon => |drag_icon| drag_icon.surface, }; if (self.wlr_surface) |wlr_surface| { wlr_surface.data = self; Signal.connect( *wlr.wlr_subsurface, self, "subsurface", Surface.onNewSubsurface, &wlr_surface.events.new_subsurface, ); Signal.connect( void, self, "commit", Surface.onCommit, &wlr_surface.events.commit, ); for ([2]*wlr.wl_list{ &wlr_surface.current.subsurfaces_below, &wlr_surface.current.subsurfaces_above, }) |subsurfaces| { var iter: *wlr.wl_list = subsurfaces.next; while (iter != subsurfaces) : (iter = iter.next) { self.onNewSubsurface(@fieldParentPtr( wlr.wlr_subsurface, "current", @fieldParentPtr(wlr.wlr_subsurface_parent_state, "link", iter), )) catch unreachable; } } } } fn unconstrainPopup(self: *Surface) void { switch (self.typed_surface) { .xdg => |xdg| { if (xdg.role == wlr.WLR_XDG_SURFACE_ROLE_POPUP) { if (self.getCenterOutput()) |output| { var box: wlr.wlr_box = undefined; output.getBox(&box); wlr.wlr_xdg_popup_unconstrain_from_box( @ptrCast(*wlr.wlr_xdg_popup, @field(xdg, wlr_xdg_surface_union).popup), &box, ); } } }, else => {}, } } fn toFront(self: *Surface) void { switch (self.typed_surface) { .xwayland => |xwayland| { wlr.wlr_xwayland_surface_restack(xwayland, null, wlr.XCB_STACK_MODE_ABOVE); }, else => {}, } } fn toBack(self: *Surface) void { switch (self.typed_surface) { .xwayland => |xwayland| { wlr.wlr_xwayland_surface_restack(xwayland, null, wlr.XCB_STACK_MODE_BELOW); }, else => {}, } } fn setKeyboardFocus(self: *Surface) void { if (self.wlr_surface) |wlr_surface| { if (self.shouldFocus()) self.server.setKeyboardFocus(wlr_surface); } } fn setGeometry(self: *Surface, box: wlr.wlr_box) void { self.output_box = box; switch (self.typed_surface) { .xdg => |xdg| { var xdg_box: wlr.wlr_box = undefined; wlr.wlr_xdg_surface_get_geometry(xdg, &xdg_box); self.output_box.x -= xdg_box.x; self.output_box.y -= xdg_box.y; self.pending_serial = wlr.wlr_xdg_toplevel_set_size( xdg, @intCast(u32, box.width), @intCast(u32, box.height), ); }, .xwayland => |xwayland| { if (self.getCenterOutput()) |output| { wlr.wlr_xwayland_surface_configure( xwayland, @intCast(i16, output.total_box.x + self.output_box.x), @intCast(i16, output.total_box.y + self.output_box.y), @intCast(u16, box.width), @intCast(u16, box.height), ); } }, else => {}, } self.updateOutputs(); self.updateBorders(); self.server.damageAllOutputs(); } fn getGeometry(self: *Surface, box: *wlr.wlr_box) void { box.x = 0; box.y = 0; switch (self.typed_surface) { .xdg => |xdg| { wlr.wlr_xdg_surface_get_geometry(xdg, box); }, .xwayland => |xwayland| { box.width = xwayland.width; box.height = xwayland.height; }, .layer => { box.width = self.output_box.width; box.height = self.output_box.height; }, else => {}, } box.x += self.output_box.x; box.y += self.output_box.y; } fn isXdgPopup(wlr_surface: *wlr.wlr_surface) bool { return std.mem.eql(u8, "xdg_popup", std.mem.span( @ptrCast(*const wlr.wlr_surface_role, wlr_surface.role).name, )); } fn adjustBoundsFromPopup(xdg_popup: *wlr.wlr_xdg_popup, parent_box: *wlr.wlr_box) void { parent_box.x += xdg_popup.geometry.x; parent_box.y += xdg_popup.geometry.y; if (@ptrCast(?*wlr.wlr_surface, xdg_popup.parent)) |parent| { if (Surface.isXdgPopup(parent)) { adjustBoundsFromPopup( @field(@ptrCast( *wlr.wlr_xdg_surface, wlr.wlr_xdg_surface_from_wlr_surface(parent), ), wlr_xdg_surface_union).popup, parent_box, ); } } } fn getParentBox(self: *Surface, box: *wlr.wlr_box) void { if (self.ancestor) |ancestor| { ancestor.getGeometry(box); } else { self.getGeometry(box); } switch (self.typed_surface) { .xdg => |xdg| { if (xdg.role == wlr.WLR_XDG_SURFACE_ROLE_POPUP) { adjustBoundsFromPopup( @field(xdg, wlr_xdg_surface_union).popup, box, ); } }, .subsurface => |subsurface| { var parent: *wlr.wlr_surface = subsurface.parent; if (Surface.isXdgPopup(parent)) { adjustBoundsFromPopup( @field(@ptrCast( *wlr.wlr_xdg_surface, wlr.wlr_xdg_surface_from_wlr_surface(parent), ), wlr_xdg_surface_union).popup, box, ); } }, else => {}, } } fn getLayoutBox(self: *Surface, box: *wlr.wlr_box) void { if (self.wlr_surface) |wlr_surface| { var parent_box: wlr.wlr_box = undefined; self.getParentBox(&parent_box); box.width = wlr_surface.current.width; box.height = wlr_surface.current.height; box.x = parent_box.x + wlr_surface.sx; box.y = parent_box.y + wlr_surface.sy; } } const UpdateOutput = struct { wlr_output: *wlr.wlr_output, enter: bool, }; fn updateOutputIter( surf: [*c]wlr.wlr_surface, _: i32, _: i32, data: ?*anyopaque, ) callconv(.C) void { const uo = @ptrCast(*UpdateOutput, @alignCast(@alignOf(*UpdateOutput), data)); const wlr_surface = @ptrCast(*wlr.wlr_surface, surf); if (uo.enter) { wlr.wlr_surface_send_enter(wlr_surface, uo.wlr_output); if (Surface.fromWlrSurface(wlr_surface)) |s| s.unconstrainPopup(); } else { wlr.wlr_surface_send_leave(wlr_surface, uo.wlr_output); } } fn updateOutputs(self: *Surface) void { var box: wlr.wlr_box = undefined; self.getLayoutBox(&box); var iter = self.server.outputs.first; while (iter) |node| : (iter = node.next) { var output_box: wlr.wlr_box = undefined; node.data.getBox(&output_box); var intersection: wlr.wlr_box = undefined; var uo = UpdateOutput{ .wlr_output = node.data.wlr_output, .enter = wlr.wlr_box_intersection(&intersection, &output_box, &box), }; self.forEachSurface(updateOutputIter, &uo, false); self.forEachSurface(updateOutputIter, &uo, true); } } fn damage(self: *Surface, whole: bool) void { if (self.server.config.damage_tracking == .minimal) { self.server.damageAllOutputs(); return; } var box: wlr.wlr_box = undefined; self.getLayoutBox(&box); var iter = self.server.outputs.first; while (iter) |node| : (iter = node.next) { const layout = node.data.getLayout(); var intersection: wlr.wlr_box = undefined; var output_box: wlr.wlr_box = undefined; node.data.getBox(&output_box); if (wlr.wlr_box_intersection(&intersection, &output_box, &box)) { var ddata = DamageData{ .output = node.data, .whole = whole, .box = wlr.wlr_box{ .width = box.width, .height = box.height, .x = box.x - layout.x, .y = box.y - layout.y, }, }; self.forEachSurface(damageIter, &ddata, false); } } } const DamageData = struct { output: *Output, box: wlr.wlr_box, whole: bool, }; fn damageIter( surf: [*c]wlr.wlr_surface, sx: i32, sy: i32, data: ?*anyopaque, ) callconv(.C) void { const ddata = @ptrCast(*DamageData, @alignCast(@alignOf(*DamageData), data)); const wlr_surface = @ptrCast(*wlr.wlr_surface, surf); var box = ddata.box; box.x += sx; box.y += sy; scaleBox(&box, ddata.output.wlr_output.scale); if (wlr.pixman_region32_not_empty(&wlr_surface.buffer_damage) != 0) { var pixman_damage: wlr.pixman_region32_t = undefined; wlr.pixman_region32_init(&pixman_damage); wlr.wlr_surface_get_effective_damage(wlr_surface, &pixman_damage); wlr.wlr_region_scale(&pixman_damage, &pixman_damage, ddata.output.wlr_output.scale); if (@floatToInt(i32, @ceil(ddata.output.wlr_output.scale)) > wlr_surface.current.scale) { wlr.wlr_region_expand( &pixman_damage, &pixman_damage, @floatToInt(i32, @ceil(ddata.output.wlr_output.scale)) - wlr_surface.current.scale, ); } wlr.pixman_region32_translate(&pixman_damage, box.x, box.y); wlr.wlr_output_damage_add(ddata.output.damage, &pixman_damage); wlr.pixman_region32_fini(&pixman_damage); } if (ddata.whole) { wlr.wlr_output_damage_add_box(ddata.output.damage, &box); } if (wlr.wl_list_empty(&wlr_surface.current.frame_callback_list) == 0) { wlr.wlr_output_schedule_frame(ddata.output.wlr_output); } } fn forEachSurface( self: *Surface, cb: fn ([*c]wlr.wlr_surface, i32, i32, ?*anyopaque) callconv(.C) void, data: *anyopaque, popups: bool, ) void { switch (self.typed_surface) { .xdg => |xdg| { if (!popups) { wlr.wlr_xdg_surface_for_each_surface(xdg, cb, data); } else { wlr.wlr_xdg_surface_for_each_popup_surface(xdg, cb, data); } }, .layer => |layer_surface| { if (!popups) { wlr.wlr_layer_surface_v1_for_each_surface(layer_surface, cb, data); } else { wlr.wlr_layer_surface_v1_for_each_popup_surface(layer_surface, cb, data); } }, else => { wlr.wlr_surface_for_each_surface(self.wlr_surface, cb, data); }, } } fn surfaceAt(self: *Surface, x: f64, y: f64, sx: *f64, sy: *f64) ?*wlr.wlr_surface { const vx = x - @intToFloat(f64, self.output_box.x); const vy = y - @intToFloat(f64, self.output_box.y); switch (self.typed_surface) { .xdg => |xdg| { return wlr.wlr_xdg_surface_surface_at(xdg, vx, vy, sx, sy); }, .xwayland => |xwayland| { if (wlr.wlr_box_contains_point(&wlr.wlr_box{ .x = self.output_box.x, .y = self.output_box.y, .width = xwayland.width, .height = xwayland.height, }, x, y)) { return wlr.wlr_surface_surface_at(self.wlr_surface, vx, vy, sx, sy); } }, .layer => |layer_surface| { if (layer_surface.mapped) { return wlr.wlr_layer_surface_v1_surface_at(layer_surface, vx, vy, sx, sy); } }, else => {}, } return null; } fn updateBorders(self: *Surface) void { if (!self.has_border) return; var box: wlr.wlr_box = undefined; self.getGeometry(&box); box.x -= self.output_box.x; box.y -= self.output_box.y; var border_left: i32 = box.x - self.server.config.active_border_width; var border_top: i32 = box.y - self.server.config.active_border_width; self.borders = .{ .{ // top .x = border_left, .y = border_top, .width = box.width + 2 * self.server.config.active_border_width, .height = self.server.config.active_border_width, }, .{ // left .x = border_left, .y = border_top + self.server.config.active_border_width, .width = self.server.config.active_border_width, .height = box.height, }, .{ // right .x = border_left + box.width + self.server.config.active_border_width, .y = border_top + self.server.config.active_border_width, .width = self.server.config.active_border_width, .height = box.height, }, .{ // bottom .x = border_left, .y = border_top + box.height + self.server.config.active_border_width, .width = box.width + 2 * self.server.config.active_border_width, .height = self.server.config.active_border_width, }, }; self.damageBorders(); } fn damageBorders(self: *Surface) void { if (self.has_border) { var iter = self.server.outputs.first; var parent_box: wlr.wlr_box = undefined; self.getParentBox(&parent_box); while (iter) |node| : (iter = node.next) { const layout = @ptrCast( *wlr.wlr_output_layout_output, wlr.wlr_output_layout_get( self.server.wlr_output_layout, node.data.wlr_output, ), ); for (self.borders) |border| { var box = border; box.x -= layout.x - parent_box.x; box.y -= layout.y - parent_box.y; scaleBox(&box, node.data.wlr_output.scale); wlr.wlr_output_damage_add_box(node.data.damage, &box); } } } } fn getAppId(self: *Surface) [*:0]const u8 { return switch (self.typed_surface) { .xdg => |xdg| @ptrCast( *wlr.wlr_xdg_toplevel, @field(xdg, wlr_xdg_surface_union).toplevel, ).app_id, .xwayland => |xwayland| xwayland.class, else => "", }; } fn getCenterOutput(self: *Surface) ?*Output { return self.server.outputAt( @intToFloat(f64, self.output_box.x + @divFloor(self.output_box.width, 2)), @intToFloat(f64, self.output_box.y + @divFloor(self.output_box.height, 2)), ); } fn fromWlrSurface(wlr_surface: ?*wlr.wlr_surface) ?*Surface { if (wlr_surface) |surface| { return @ptrCast(?*Surface, @alignCast(@alignOf(?*Surface), surface.data)); } return null; } fn getToplevel(self: *Surface) ?*Surface { if (self.has_border) { return self; } else if (self.ancestor) |ancestor| { return ancestor.getToplevel(); } else { return null; } } fn move( self: *Surface, dir: Config.Direction, pixels: u32, comptime abscissa: []const u8, comptime ordinate: []const u8, ) void { if (self.getCenterOutput()) |output| { var box: wlr.wlr_box = undefined; self.getGeometry(&box); const factor = @floatToInt( i32, @intToFloat(f64, pixels) / output.wlr_output.scale, ); const delta_abscissa: i32 = switch (dir) { .left => -1, .right => 1, else => 0, }; const delta_ordinate: i32 = switch (dir) { .up => -1, .down => 1, else => 0, }; @field(box, abscissa) += factor * delta_abscissa; @field(box, ordinate) += factor * delta_ordinate; self.setGeometry(box); } } fn toggleFullscreen(self: *Surface) void { if (self.is_actual_fullscreen) { self.is_actual_fullscreen = false; self.setGeometry(self.pre_fullscreen_position); } else { if (self.getCenterOutput()) |output| { self.is_actual_fullscreen = true; self.getGeometry(&self.pre_fullscreen_position); self.setGeometry(output.total_box); } } } fn place(self: *Surface) void { if (self.server.outputAtCursor()) |output| { self.workspace = output.active_workspace; } var parent_box = wlr.wlr_box{ .x = 0, .y = 0, .width = 0, .height = 0 }; var box: wlr.wlr_box = undefined; self.getGeometry(&box); switch (self.typed_surface) { .xdg => |xdg| { if (xdg.role == wlr.WLR_XDG_SURFACE_ROLE_TOPLEVEL) { if (@ptrCast(?*wlr.wlr_xdg_surface, @ptrCast( *wlr.wlr_xdg_toplevel, @field(xdg, wlr_xdg_surface_union).toplevel, ).parent)) |parent_xdg| { if (Surface.fromWlrSurface(parent_xdg.surface)) |parent| { parent.getGeometry(&parent_box); } } } }, else => {}, } if (parent_box.width == 0) { if (self.server.outputAtCursor()) |output| { output.getBox(&parent_box); } } if (parent_box.width == 0) { if (self.server.outputs.first) |node| { node.data.getBox(&parent_box); } } box.x = parent_box.x + @divFloor(parent_box.width, 2) - @divFloor(box.width, 2); box.y = parent_box.y + @divFloor(parent_box.height, 2) - @divFloor(box.height, 2); self.setGeometry(box); } fn initDamageRender( box: wlr.wlr_box, region: *wlr.pixman_region32_t, output_damage: *wlr.pixman_region32_t, ) ?[]wlr.pixman_box32_t { wlr.pixman_region32_init(region); _ = wlr.pixman_region32_union_rect( region, region, box.x, box.y, @intCast(u32, box.width), @intCast(u32, box.height), ); _ = wlr.pixman_region32_intersect(region, region, output_damage); if (wlr.pixman_region32_not_empty(region) != 0) { var num_rects: i32 = undefined; var rects: [*c]wlr.pixman_box32_t = wlr.pixman_region32_rectangles(region, &num_rects); return rects[0..@intCast(usize, num_rects)]; } return null; } fn scaleLength(length: i32, offset: i32, scale: f64) i32 { return @floatToInt(i32, @round(@intToFloat(f64, offset + length) * scale) - @round(@intToFloat(f64, offset) * scale)); } fn scaleBox(box: *wlr.wlr_box, scale: f64) void { box.x = @floatToInt(i32, @round(@intToFloat(f64, box.x) * scale)); box.y = @floatToInt(i32, @round(@intToFloat(f64, box.y) * scale)); box.width = scaleLength(box.width, box.x, scale); box.height = scaleLength(box.height, box.x, scale); } fn renderFirstFullscreen(surfaces: std.TailQueue(*Surface), rdata: *RenderData) bool { var iter = surfaces.last; return while (iter) |node| : (iter = node.prev) { if (node.data.is_actual_fullscreen and node.data.isVisibleOn(rdata.output, false)) { node.data.triggerRender(rdata, false); break true; } } else false; } fn renderList( surfaces: std.TailQueue(*Surface), rdata: *RenderData, popups: bool, ) void { rdata.spread.set(surfaces, rdata.output); var iter = surfaces.last; rdata.spread.index = 0; while (iter) |node| : (iter = node.prev) { if (!node.data.isVisibleOn(rdata.output, false)) continue; node.data.triggerRender(rdata, popups); if (rdata.output.spread_view) rdata.spread.index += 1; } } fn isVisible(self: *Surface, any_workspace: bool) bool { var iter = self.server.outputs.first; return while (iter) |node| : (iter = node.next) { if (self.isVisibleOn(node.data, any_workspace)) break true; } else false; } fn isVisibleOn(self: *Surface, output: *Output, any_workspace: bool) bool { if (!any_workspace and self.workspace != 0 and self.workspace != output.active_workspace) return false; var box: wlr.wlr_box = undefined; self.getGeometry(&box); return wlr.wlr_output_layout_intersects( output.server.wlr_output_layout, output.wlr_output, &box, ); } fn triggerRender(self: *Surface, rdata: *RenderData, popups: bool) void { switch (self.typed_surface) { .xdg, .xwayland => { if (rdata.output.spread_view) { const col = @intCast(i32, @rem(rdata.spread.index, rdata.spread.cols)); const row = @intCast(i32, @divFloor(rdata.spread.index, rdata.spread.cols)); rdata.x = col * rdata.spread.width + rdata.spread.margin_x + rdata.spread.layout.x; rdata.y = row * rdata.spread.height + rdata.spread.margin_y + rdata.spread.layout.y; rdata.spread.scale = @minimum( @intToFloat(f32, rdata.spread.width - 2 * rdata.spread.margin_x) / @intToFloat(f32, self.output_box.width), @intToFloat(f32, rdata.spread.height - 2 * rdata.spread.margin_y) / @intToFloat(f32, self.output_box.height), ); } else { rdata.x = self.output_box.x; rdata.y = self.output_box.y; } }, .drag_icon => |drag_icon| { if (!drag_icon.mapped or rdata.output != self.server.outputAtCursor()) return; rdata.x = @floatToInt(i32, self.server.cursor.x); rdata.y = @floatToInt(i32, self.server.cursor.y); }, else => { rdata.x = self.output_box.x; rdata.y = self.output_box.y; }, } self.forEachSurface(renderIter, rdata, popups); } fn renderIter( surf: [*c]wlr.wlr_surface, sx: i32, sy: i32, data: ?*anyopaque, ) callconv(.C) void { if (Surface.fromWlrSurface(@ptrCast(*wlr.wlr_surface, surf))) |surface| { surface.render(@ptrCast(*RenderData, @alignCast(@alignOf(*RenderData), data)), sx, sy); } else { std.log.err("Could not find surface to render: {s}", .{@ptrCast(*const wlr.wlr_surface_role, @ptrCast(*wlr.wlr_surface, surf).role).name}); } } fn render(self: *Surface, rdata: *RenderData, sx: i32, sy: i32) void { if (self.wlr_surface) |wlr_surface| { if (wlr.wlr_surface_get_texture(wlr_surface)) |texture| { var oxf: f64 = 0; var oyf: f64 = 0; wlr.wlr_output_layout_output_coords( rdata.output.server.wlr_output_layout, rdata.output.wlr_output, &oxf, &oyf, ); oxf += @intToFloat(f64, rdata.x + sx); oyf += @intToFloat(f64, rdata.y + sy); const ox = @floatToInt(i32, oxf); const oy = @floatToInt(i32, oyf); var region: wlr.pixman_region32_t = undefined; if (self.has_border and !rdata.output.spread_view) { const color = if (self == rdata.output.server.grabbed_toplevel) &rdata.output.server.config.grabbed_color else if (wlr_surface == rdata.output.server.seat.keyboard_state.focused_surface) &rdata.output.server.config.focused_color else &rdata.output.server.config.border_color; for (self.borders) |border| { var b = border; b.x += ox; b.y += oy; scaleBox(&b, rdata.output.wlr_output.scale); if (initDamageRender(b, &region, rdata.damage)) |rects| { for (rects) |rect| { scissor(rdata.output.wlr_output, rect); wlr.wlr_render_rect( rdata.output.wlr_output.renderer, &b, color, &rdata.output.wlr_output.transform_matrix, ); } } wlr.pixman_region32_fini(&region); } } var box = wlr.wlr_box{ .x = ox, .y = oy, .width = @floatToInt(i32, @intToFloat(f32, wlr_surface.current.width) * rdata.spread.scale), .height = @floatToInt(i32, @intToFloat(f32, wlr_surface.current.height) * rdata.spread.scale), }; scaleBox(&box, rdata.output.wlr_output.scale); var matrix: [9]f32 = undefined; const transform = wlr.wlr_output_transform_invert(wlr_surface.current.transform); wlr.wlr_matrix_project_box(&matrix, &box, transform, 0, &rdata.output.wlr_output.transform_matrix); if (initDamageRender(box, &region, rdata.damage)) |rects| { for (rects) |rect| { scissor(rdata.output.wlr_output, rect); _ = wlr.wlr_render_texture_with_matrix(rdata.output.wlr_output.renderer, texture, &matrix, 1); } } wlr.pixman_region32_fini(&region); wlr.wlr_surface_send_frame_done(wlr_surface, &rdata.when); wlr.wlr_presentation_surface_sampled_on_output( rdata.output.server.presentation, wlr_surface, rdata.output.wlr_output, ); } } } fn setActivated(self: *Surface, activated: bool) bool { switch (self.typed_surface) { .xdg => |xdg| { if (xdg.role == wlr.WLR_XDG_SURFACE_ROLE_TOPLEVEL) { _ = wlr.wlr_xdg_toplevel_set_activated(xdg, activated); return true; } }, .xwayland => |xwayland| { wlr.wlr_xwayland_surface_activate(xwayland, activated); if (activated) { wlr.wlr_xwayland_surface_restack(xwayland, null, wlr.XCB_STACK_MODE_ABOVE); } return true; }, .layer => return true, else => {}, } return false; } const SurfaceType = enum { xdg, xwayland, layer, subsurface, drag_icon }; node: std.TailQueue(*Surface).Node, list: ?*std.TailQueue(*Surface), server: *Server, ancestor: ?*Surface, typed_surface: union(SurfaceType) { xdg: *wlr.wlr_xdg_surface, xwayland: *wlr.wlr_xwayland_surface, layer: *wlr.wlr_layer_surface_v1, subsurface: *wlr.wlr_subsurface, drag_icon: *wlr.wlr_drag_icon, }, wlr_surface: ?*wlr.wlr_surface, mapped: bool, layer: wlr.zwlr_layer_shell_v1_layer, output_box: wlr.wlr_box, activate: wlr.wl_listener, configure: wlr.wl_listener, popup: wlr.wl_listener, subsurface: wlr.wl_listener, map: wlr.wl_listener, unmap: wlr.wl_listener, commit: wlr.wl_listener, destroy: wlr.wl_listener, request_fullscreen: wlr.wl_listener, is_requested_fullscreen: bool, has_border: bool, borders: [4]wlr.wlr_box, is_actual_fullscreen: bool, pre_fullscreen_position: wlr.wlr_box, workspace: u32, pending_serial: u32, }; const Keyboard = struct { fn create(server: *Server, device: *wlr.wlr_input_device) !?*Keyboard { var keyboard = try alloc.create(Keyboard); keyboard.init(server, device); return keyboard; } fn init(self: *Keyboard, server: *Server, device: *wlr.wlr_input_device) void { self.node.data = self; self.server = server; self.device = device; self.wlr_keyboard = @field(device, wlr_input_device_union).keyboard; self.captured_modifiers = 0; self.server.keyboards.append(&self.node); var context = wlr.xkb_context_new(wlr.XKB_CONTEXT_NO_FLAGS); var keymap = wlr.xkb_keymap_new_from_names( context, null, wlr.XKB_KEYMAP_COMPILE_NO_FLAGS, ); _ = wlr.wlr_keyboard_set_keymap(self.wlr_keyboard, keymap); wlr.xkb_keymap_unref(keymap); wlr.xkb_context_unref(context); wlr.wlr_keyboard_set_repeat_info(self.wlr_keyboard, 25, 600); Signal.connect( void, self, "modifiers", Keyboard.onModifiers, &self.wlr_keyboard.events.modifiers, ); Signal.connect( *wlr.wlr_event_keyboard_key, self, "key", Keyboard.onKey, &self.wlr_keyboard.events.key, ); wlr.wlr_seat_set_keyboard(server.seat, device); } fn onModifiers(self: *Keyboard, _: void) !void { wlr.wlr_seat_set_keyboard(self.server.seat, self.device); wlr.wlr_seat_keyboard_notify_modifiers(self.server.seat, &self.wlr_keyboard.modifiers); if (self.wlr_keyboard.modifiers.depressed == 0 and self.captured_modifiers != 0) { self.captured_modifiers = 0; self.server.reportHotkeyModifierState(false); } } fn onKey(self: *Keyboard, event: *wlr.wlr_event_keyboard_key) !void { wlr.wlr_idle_notify_activity(self.server.idle, self.server.seat); var handled = false; const keycode: u32 = event.keycode + 8; var syms: [*c]wlr.xkb_keysym_t = undefined; const nsyms = wlr.xkb_state_key_get_syms(self.wlr_keyboard.xkb_state, keycode, &syms); if (nsyms > 0) { const modifiers: u32 = wlr.wlr_keyboard_get_modifiers(self.wlr_keyboard); if (event.state == wlr.WL_KEYBOARD_KEY_STATE_PRESSED) { if (self.server.outputAtCursor()) |output| { if (output.spread_view and modifiers == 0 and syms[0] == wlr.XKB_KEY_Escape) { output.toggleSpreadView(); return; } } if (self.server.input_inhibit_mgr.active_inhibitor == null) { for (syms[0..@intCast(usize, nsyms)]) |symbol| { handled = self.handleKeybinding(modifiers, symbol) or handled; if (handled) break; } } } } if (!handled) { wlr.wlr_seat_set_keyboard(self.server.seat, self.device); wlr.wlr_seat_keyboard_notify_key( self.server.seat, event.time_msec, event.keycode, event.state, ); } } fn handleKeybinding(self: *Keyboard, modifiers: u32, symbol: wlr.xkb_keysym_t) bool { for (self.server.config.hotkeys) |hotkey| { if (hotkey.modifiers == modifiers and hotkey.key == symbol) { if (modifiers != 0) { self.captured_modifiers = modifiers; self.server.reportHotkeyModifierState(true); } hotkey.cb(self.server, hotkey.arg); return true; } } return false; } node: std.TailQueue(*Keyboard).Node, server: *Server, device: *wlr.wlr_input_device, wlr_keyboard: *wlr.wlr_keyboard, modifiers: wlr.wl_listener, key: wlr.wl_listener, captured_modifiers: u32, }; const SpreadParams = struct { fn set(self: *SpreadParams, surfaces: std.TailQueue(*Surface), output: *Output) void { self.scale = 1; if (!output.spread_view) return; var visible_count: f32 = 0; var iter = surfaces.last; while (iter) |node| : (iter = node.prev) { if (node.data.isVisibleOn(output, false)) visible_count += 1; } if (visible_count == 0) return; self.layout = output.getLayout(); self.rows = @floatToInt(u32, @sqrt(visible_count)); self.cols = @floatToInt(u32, @ceil(visible_count / @intToFloat(f64, self.rows))); var output_box: wlr.wlr_box = undefined; output.getBox(&output_box); const margin_ratio = 20; self.margin_x = @divFloor(output_box.width, margin_ratio); self.margin_y = @divFloor(output_box.height, margin_ratio); self.width = @divFloor(output_box.width, @intCast(i32, self.cols)); self.height = @divFloor(output_box.height, @intCast(i32, self.rows)); } cols: u32, rows: u32, index: u32, scale: f32, layout: *wlr.wlr_output_layout_output, margin_x: i32, margin_y: i32, width: i32, height: i32, }; const RenderData = struct { output: *Output, x: i32 = -1, y: i32 = -1, when: wlr.timespec, damage: *wlr.pixman_region32_t, spread: SpreadParams = undefined, }; fn scissor(wlr_output: *wlr.wlr_output, rect: wlr.pixman_box32_t) void { var box = wlr.wlr_box{ .x = rect.x1, .y = rect.y1, .width = rect.x2 - rect.x1, .height = rect.y2 - rect.y1, }; var ow: i32 = undefined; var oh: i32 = undefined; wlr.wlr_output_transformed_resolution(wlr_output, &ow, &oh); var transform = wlr.wlr_output_transform_invert(wlr_output.transform); wlr.wlr_box_transform(&box, &box, transform, ow, oh); wlr.wlr_renderer_scissor(wlr_output.renderer, &box); } const Output = struct { fn create(server: *Server, wlr_output: *wlr.wlr_output) !?*Output { var output = try alloc.create(Output); output.init(server, wlr_output); return output; } fn init(self: *Output, server: *Server, wlr_output: *wlr.wlr_output) void { _ = wlr.wlr_output_init_render(wlr_output, server.wlr_allocator, server.wlr_renderer); if (wlr.wl_list_empty(&wlr_output.modes) == 0) { const mode = wlr.wlr_output_preferred_mode(wlr_output); wlr.wlr_output_set_mode(wlr_output, mode); wlr.wlr_output_enable_adaptive_sync(wlr_output, true); wlr.wlr_output_enable(wlr_output, true); if (!wlr.wlr_output_commit(wlr_output)) { alloc.destroy(self); return; } } self.node.data = self; self.active_workspace = 1; self.wlr_output = wlr_output; self.server = server; self.wlr_output.data = self; self.damage = wlr.wlr_output_damage_create(wlr_output); for (LAYERS_TOP_TO_BOTTOM) |layerIndex| { self.layers[layerIndex] = std.TailQueue(*Surface){}; } self.server.outputs.append(&self.node); self.spread_view = false; wlr.wlr_output_layout_add_auto(self.server.wlr_output_layout, self.wlr_output); Signal.connect( void, self, "frame", Output.onFrame, &self.damage.events.frame, ); Signal.connect( void, self, "destroy", Output.onDestroy, &wlr_output.events.destroy, ); } fn fromWlrOutput(wlr_output: ?*wlr.wlr_output) ?*Output { if (wlr_output) |output| { return @ptrCast(?*Output, @alignCast(@alignOf(?*Output), output.data)); } return null; } fn damageAll(self: *Output) void { wlr.wlr_output_damage_add_whole(self.damage); } fn onFrame(self: *Output, _: void) !void { var now: wlr.timespec = undefined; _ = wlr.clock_gettime(wlr.CLOCK_MONOTONIC, &now); var damage: wlr.pixman_region32_t = undefined; wlr.pixman_region32_init(&damage); var needs_frame: bool = false; if (!wlr.wlr_output_damage_attach_render(self.damage, &needs_frame, &damage)) { return; } if (needs_frame) { wlr.wlr_renderer_begin( self.wlr_output.renderer, @intCast(u32, self.wlr_output.width), @intCast(u32, self.wlr_output.height), ); if (wlr.pixman_region32_not_empty(&damage) != 0) { var rdata: RenderData = .{ .output = self, .damage = &damage, .when = now }; rdata.spread.scale = 1; var nrects: i32 = undefined; for (wlr.pixman_region32_rectangles(&damage, &nrects)[0..@intCast(usize, nrects)]) |rect| { scissor(self.wlr_output, rect); wlr.wlr_renderer_clear(self.wlr_output.renderer, &self.server.config.background_color); } if (!Surface.renderFirstFullscreen(self.server.toplevels, &rdata)) { Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND], &rdata, false); Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM], &rdata, false); if (self.server.show_toplevels) Surface.renderList(self.server.toplevels, &rdata, false); if (self.server.show_toplevels) Surface.renderList(self.server.unmanaged_toplevels, &rdata, false); Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_TOP], &rdata, false); Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY], &rdata, false); } if (self.server.grabbed_toplevel) |grabbed| grabbed.triggerRender(&rdata, false); if (self.server.drag_icon) |drag_icon| drag_icon.triggerRender(&rdata, false); Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND], &rdata, true); Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM], &rdata, true); Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_TOP], &rdata, true); Surface.renderList(self.layers[wlr.ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY], &rdata, true); } wlr.wlr_renderer_scissor(self.wlr_output.renderer, null); wlr.wlr_output_render_software_cursors(self.wlr_output, null); wlr.wlr_renderer_end(self.wlr_output.renderer); wlr.wlr_output_set_damage(self.wlr_output, &self.damage.current); _ = wlr.wlr_output_commit(self.wlr_output); } else { wlr.wlr_output_rollback(self.wlr_output); } wlr.pixman_region32_fini(&damage); } fn onDestroy(self: *Output, _: void) !void { wlr.wl_list_remove(&self.frame.link); wlr.wl_list_remove(&self.destroy.link); self.server.outputs.remove(&self.node); wlr.wlr_output_layout_remove(self.server.wlr_output_layout, self.wlr_output); alloc.destroy(self); } fn onLayoutChanged(self: *Output, config: *wlr.wlr_output_configuration_v1) void { var head: *wlr.wlr_output_configuration_head_v1 = wlr.wlr_output_configuration_head_v1_create(config, self.wlr_output); self.total_box = wlr.wlr_output_layout_get_box( self.server.wlr_output_layout, self.wlr_output, ).*; self.usable_box = self.total_box; head.state.enabled = self.wlr_output.enabled; head.state.mode = self.wlr_output.current_mode; head.state.x = self.total_box.x; head.state.y = self.total_box.y; self.arrangeLayers(); self.server.ensureToplevelsVisible(); } fn arrangeLayer( self: *Output, layer_surfaces: std.TailQueue(*Surface), usable_area: *wlr.wlr_box, exclusive: bool, ) void { const both_horiz: u32 = LAYER_ANCHOR_LEFT | LAYER_ANCHOR_RIGHT; const both_vert: u32 = LAYER_ANCHOR_TOP | LAYER_ANCHOR_BOTTOM; var iter = layer_surfaces.first; while (iter) |node| : (iter = node.next) { var surface = node.data; var state: *wlr.wlr_layer_surface_v1_state = &surface.typed_surface.layer.current; if (exclusive != (state.exclusive_zone > 0)) { continue; } var new_x: i32 = undefined; var new_y: i32 = undefined; var new_width = @intCast(i32, state.desired_width); var new_height = @intCast(i32, state.desired_height); var bounds: wlr.wlr_box = if (state.exclusive_zone == -1) self.total_box else usable_area.*; // Horizontal axis if (((state.anchor & both_horiz) != 0) and new_width == 0) { new_x = bounds.x; new_width = bounds.width; } else if ((state.anchor & LAYER_ANCHOR_LEFT) != 0) { new_x = bounds.x; } else if ((state.anchor & LAYER_ANCHOR_RIGHT) != 0) { new_x = bounds.x + bounds.width - new_width; } else { new_x = bounds.x + @divFloor(bounds.width, 2) - @divFloor(new_width, 2); } // Vertical axis if (((state.anchor & both_vert) != 0) and new_height == 0) { new_y = bounds.y; new_height = bounds.height; } else if ((state.anchor & LAYER_ANCHOR_TOP) != 0) { new_y = bounds.y; } else if ((state.anchor & LAYER_ANCHOR_BOTTOM) != 0) { new_y = bounds.y + bounds.height - new_height; } else { new_y = bounds.y + @divFloor(bounds.height, 2) - @divFloor(new_height, 2); } // Margin if ((state.anchor & both_horiz) == both_horiz) { new_x += state.margin.left; new_width -= state.margin.left + state.margin.right; } else if ((state.anchor & LAYER_ANCHOR_LEFT) != 0) { new_x += state.margin.left; } else if ((state.anchor & LAYER_ANCHOR_RIGHT) != 0) { new_x -= state.margin.right; } if ((state.anchor & both_vert) == both_vert) { new_y += state.margin.top; new_height -= state.margin.top + state.margin.bottom; } else if ((state.anchor & LAYER_ANCHOR_TOP) != 0) { new_y += state.margin.top; } else if ((state.anchor & LAYER_ANCHOR_BOTTOM) != 0) { new_y -= state.margin.bottom; } if (new_width < 0 or new_height < 0) { wlr.wlr_layer_surface_v1_destroy(surface.typed_surface.layer); continue; } surface.output_box = wlr.wlr_box{ .x = @intCast(i32, new_x), .y = @intCast(i32, new_y), .width = @intCast(i32, new_width), .height = @intCast(i32, new_height), }; if (state.exclusive_zone > 0) handleLayerExclusives( usable_area, state.anchor, state.exclusive_zone, state.margin.top, state.margin.right, state.margin.bottom, state.margin.left, ); _ = wlr.wlr_layer_surface_v1_configure( surface.typed_surface.layer, @intCast(u32, new_width), @intCast(u32, new_height), ); } } fn arrangeLayers(self: *Output) void { var updated_usable_box = self.total_box; for (LAYERS_TOP_TO_BOTTOM) |layer| { self.arrangeLayer(self.layers[layer], &updated_usable_box, true); } if (!std.meta.eql(updated_usable_box, self.usable_box)) { self.usable_box = updated_usable_box; // TODO: move toplevels to avoid? } for (LAYERS_TOP_TO_BOTTOM) |layer| { self.arrangeLayer(self.layers[layer], &updated_usable_box, false); } self.damageAll(); } fn layerSurfaceAt( self: *Output, layer: wlr.zwlr_layer_shell_v1_layer, x: f64, y: f64, sx: *f64, sy: *f64, ) ?*wlr.wlr_surface { var iter = self.layers[layer].last; return while (iter) |node| : (iter = node.prev) { if (node.data.surfaceAt(x, y, sx, sy)) |wlr_surface| { break wlr_surface; } } else null; } fn handleLayerExclusives( usable_area: *wlr.wlr_box, anchor: u32, exclusive: i32, margin_top: i32, margin_right: i32, margin_bottom: i32, margin_left: i32, ) void { const Edge = struct { singular_anchor: u32, anchor_triplet: u32, positive_axis: ?*i32, negative_axis: ?*i32, margin: i32, }; const edges: [4]Edge = .{ .{ // Top .singular_anchor = LAYER_ANCHOR_TOP, .anchor_triplet = LAYER_ANCHOR_LEFT | LAYER_ANCHOR_RIGHT | LAYER_ANCHOR_TOP, .positive_axis = &usable_area.y, .negative_axis = &usable_area.height, .margin = margin_top, }, .{ // Bottom .singular_anchor = LAYER_ANCHOR_BOTTOM, .anchor_triplet = LAYER_ANCHOR_LEFT | LAYER_ANCHOR_RIGHT | LAYER_ANCHOR_BOTTOM, .positive_axis = null, .negative_axis = &usable_area.height, .margin = margin_bottom, }, .{ // Left .singular_anchor = LAYER_ANCHOR_LEFT, .anchor_triplet = LAYER_ANCHOR_LEFT | LAYER_ANCHOR_TOP | LAYER_ANCHOR_BOTTOM, .positive_axis = &usable_area.x, .negative_axis = &usable_area.width, .margin = margin_left, }, .{ // Right .singular_anchor = LAYER_ANCHOR_RIGHT, .anchor_triplet = LAYER_ANCHOR_RIGHT | LAYER_ANCHOR_TOP | LAYER_ANCHOR_BOTTOM, .positive_axis = null, .negative_axis = &usable_area.width, .margin = margin_right, }, }; for (edges) |*edge| { if ((anchor == edge.singular_anchor or anchor == edge.anchor_triplet) and exclusive + @intCast(i32, edge.margin) > 0) { if (edge.positive_axis) |*positive_axis| { positive_axis.*.* += exclusive + @intCast(i32, edge.margin); } if (edge.negative_axis) |*negative_axis| { negative_axis.*.* -= exclusive + @intCast(i32, edge.margin); } break; } } } fn getLayout(self: *Output) *wlr.wlr_output_layout_output { return @ptrCast( *wlr.wlr_output_layout_output, wlr.wlr_output_layout_get(self.server.wlr_output_layout, self.wlr_output), ); } fn getBox(self: *Output, box: *wlr.wlr_box) void { const layout = self.getLayout(); box.x = layout.x; box.y = layout.y; wlr.wlr_output_effective_resolution( self.wlr_output, &box.width, &box.height, ); } fn toggleSpreadView(self: *Output) void { self.spread_view = !self.spread_view; self.damageAll(); } const LAYERS_TOP_TO_BOTTOM: [LAYER_COUNT]usize = .{ wlr.ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY, wlr.ZWLR_LAYER_SHELL_V1_LAYER_TOP, wlr.ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM, wlr.ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND, }; const LAYER_COUNT = 4; const LAYER_ANCHOR_TOP = wlr.ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP; const LAYER_ANCHOR_LEFT = wlr.ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT; const LAYER_ANCHOR_BOTTOM = wlr.ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM; const LAYER_ANCHOR_RIGHT = wlr.ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT; node: std.TailQueue(*Output).Node, server: *Server, wlr_output: *wlr.wlr_output, frame: wlr.wl_listener, destroy: wlr.wl_listener, total_box: wlr.wlr_box, usable_box: wlr.wlr_box, layers: [LAYER_COUNT]std.TailQueue(*Surface), active_workspace: u32, damage: *wlr.wlr_output_damage, spread_view: bool, }; const Server = struct { fn init(self: *Server) !void { self.config.init(); self.drag_icon = null; self.grabbed_toplevel = null; self.modifier_pressed = false; self.show_toplevels = true; wlr.wlr_log_init(wlr.WLR_DEBUG, null); self.wl_display = wlr.wl_display_create() orelse return error.CannotCreateDisplay; self.wlr_backend = wlr.wlr_backend_autocreate(self.wl_display) orelse return error.CannotCreateBackend; self.wlr_renderer = wlr.wlr_renderer_autocreate(self.wlr_backend) orelse return error.CannotGetRenderer; _ = wlr.wlr_renderer_init_wl_display(self.wlr_renderer, self.wl_display); self.wlr_allocator = wlr.wlr_allocator_autocreate(self.wlr_backend, self.wlr_renderer); var compositor: *wlr.wlr_compositor = wlr.wlr_compositor_create( self.wl_display, self.wlr_renderer, ) orelse return error.CannotCreateCompositor; _ = wlr.wlr_data_device_manager_create(self.wl_display); _ = wlr.wlr_primary_selection_v1_device_manager_create(self.wl_display); _ = wlr.wlr_export_dmabuf_manager_v1_create(self.wl_display); _ = wlr.wlr_screencopy_manager_v1_create(self.wl_display); _ = wlr.wlr_data_control_manager_v1_create(self.wl_display); _ = wlr.wlr_gamma_control_manager_v1_create(self.wl_display); _ = wlr.wlr_viewporter_create(self.wl_display); self.wlr_output_layout = wlr.wlr_output_layout_create() orelse return error.CannotCreateOutputLayout; self.outputs = std.TailQueue(*Output){}; Signal.connect( void, self, "output_changed", Server.onOutputLayoutChanged, &self.wlr_output_layout.events.change, ); _ = wlr.wlr_xdg_output_manager_v1_create(self.wl_display, self.wlr_output_layout); Signal.connect( *wlr.wlr_output, self, "new_output", Server.onNewOutput, &self.wlr_backend.events.new_output, ); self.toplevels = std.TailQueue(*Surface){}; self.unmanaged_toplevels = std.TailQueue(*Surface){}; self.xdg_shell = wlr.wlr_xdg_shell_create(self.wl_display); Signal.connect( *wlr.wlr_xdg_surface, self, "new_xdg_surface", Server.onNewXdgSurface, &self.xdg_shell.events.new_surface, ); self.layer_shell = wlr.wlr_layer_shell_v1_create(self.wl_display); Signal.connect( *wlr.wlr_layer_surface_v1, self, "new_layer_surface", Server.onNewLayerSurface, &self.layer_shell.events.new_surface, ); self.cursor_mode = .passthrough; self.cursor = wlr.wlr_cursor_create(); wlr.wlr_cursor_attach_output_layout(self.cursor, self.wlr_output_layout); self.cursor_mgr = wlr.wlr_xcursor_manager_create(null, 24); _ = wlr.wlr_xcursor_manager_load(self.cursor_mgr, 1); Signal.connect( *wlr.wlr_event_pointer_motion, self, "cursor_motion", Server.onCursorMotion, &self.cursor.events.motion, ); Signal.connect( *wlr.wlr_event_pointer_motion_absolute, self, "cursor_motion_absolute", Server.onCursorMotionAbsolute, &self.cursor.events.motion_absolute, ); Signal.connect( *wlr.wlr_event_pointer_button, self, "cursor_button", Server.onCursorButton, &self.cursor.events.button, ); Signal.connect( *wlr.wlr_event_pointer_axis, self, "cursor_axis", Server.onCursorAxis, &self.cursor.events.axis, ); Signal.connect( void, self, "cursor_frame", Server.onCursorFrame, &self.cursor.events.frame, ); self.keyboards = std.TailQueue(*Keyboard){}; Signal.connect( *wlr.wlr_input_device, self, "new_input", Server.onNewInputDevice, &self.wlr_backend.events.new_input, ); self.seat = wlr.wlr_seat_create(self.wl_display, "seat0"); Signal.connect( *wlr.wlr_seat_pointer_request_set_cursor_event, self, "request_cursor", Server.onRequestSetCursor, &self.seat.events.request_set_cursor, ); Signal.connect( *wlr.wlr_seat_request_set_selection_event, self, "request_set_selection", Server.onRequestSetSelection, &self.seat.events.request_set_selection, ); Signal.connect( *wlr.wlr_seat_request_set_primary_selection_event, self, "request_set_primary_selection", Server.onRequestSetPrimarySelection, &self.seat.events.request_set_primary_selection, ); Signal.connect( *wlr.wlr_seat_request_start_drag_event, self, "request_start_drag", Server.onRequestStartDrag, &self.seat.events.request_start_drag, ); Signal.connect( *wlr.wlr_drag, self, "start_drag", Server.onStartDrag, &self.seat.events.start_drag, ); wlr.wlr_server_decoration_manager_set_default_mode( wlr.wlr_server_decoration_manager_create(self.wl_display), wlr.WLR_SERVER_DECORATION_MANAGER_MODE_SERVER, ); _ = wlr.wlr_xdg_decoration_manager_v1_create(self.wl_display); self.input_inhibit_mgr = wlr.wlr_input_inhibit_manager_create(self.wl_display); self.idle = wlr.wlr_idle_create(self.wl_display); self.output_manager = wlr.wlr_output_manager_v1_create(self.wl_display); Signal.connect( *wlr.wlr_output_configuration_v1, self, "output_manager_apply", Server.onOutputManagerApply, &self.output_manager.events.apply, ); Signal.connect( *wlr.wlr_output_configuration_v1, self, "output_manager_test", Server.onOutputManagerTest, &self.output_manager.events.@"test", ); self.presentation = wlr.wlr_presentation_create(self.wl_display, self.wlr_backend); self.xwayland = wlr.wlr_xwayland_create(self.wl_display, compositor, true); if (self.xwayland) |xwayland| { Signal.connect( void, self, "xwayland_ready", Server.onXwaylandReady, &xwayland.events.ready, ); Signal.connect( *wlr.wlr_xwayland_surface, self, "new_xwayland_surface", Server.onNewXwaylandSurface, &xwayland.events.new_surface, ); if (wlr.setenv("DISPLAY", xwayland.display_name, 1) == -1) { std.log.err("Failed to set DISPLAY env var for xwayland", .{}); } } else { std.log.err("Failed to setup XWayland X server, continuing without it", .{}); } } fn deinit(self: *Server) void { std.log.info("Shutting down Byway", .{}); if (self.xwayland) |xwayland| { wlr.wlr_xwayland_destroy(xwayland); } wlr.wl_display_destroy_clients(self.wl_display); wlr.wl_display_destroy(self.wl_display); wlr.wlr_xcursor_manager_destroy(self.cursor_mgr); wlr.wlr_cursor_destroy(self.cursor); wlr.wlr_output_layout_destroy(self.wlr_output_layout); } fn start(self: *Server) !void { const socket = wlr.wl_display_add_socket_auto(self.wl_display) orelse return error.CannotAddSocket; if (!wlr.wlr_backend_start(self.wlr_backend)) { return error.CannotStartBackend; } if (wlr.setenv("WAYLAND_DISPLAY", socket, 1) == -1) { return error.CannotSetWaylandDisplayVar; } std.log.info("Running Byway on WAYLAND_DISPLAY={s}", .{socket}); for (self.config.autostart.items) |cmd| { std.log.info("cmd {s}", .{cmd}); self.actionCmd(cmd); } wlr.wl_display_run(self.wl_display); } fn onOutputLayoutChanged(self: *Server, _: void) !void { var config = wlr.wlr_output_configuration_v1_create(); var iter = self.outputs.first; while (iter) |node| : (iter = node.next) { node.data.onLayoutChanged(config); } wlr.wlr_output_manager_v1_set_configuration(self.output_manager, config); } fn onNewOutput(self: *Server, wlr_output: *wlr.wlr_output) !void { _ = try Output.create(self, wlr_output); } fn onNewXdgSurface(self: *Server, xdg_surface: *wlr.wlr_xdg_surface) !void { _ = try Surface.create(self, xdg_surface, null); } fn onNewXwaylandSurface(self: *Server, xwayland_surface: *wlr.wlr_xwayland_surface) !void { _ = try Surface.create(self, xwayland_surface, null); } fn onNewLayerSurface(self: *Server, wlr_layer_surface: *wlr.wlr_layer_surface_v1) !void { _ = try Surface.create(self, wlr_layer_surface, null); } fn onCursorMotion(self: *Server, event: *wlr.wlr_event_pointer_motion) !void { wlr.wlr_cursor_move(self.cursor, event.device, event.delta_x, event.delta_y); self.processCursorMotion(event.time_msec); } fn onCursorMotionAbsolute(self: *Server, event: *wlr.wlr_event_pointer_motion_absolute) !void { wlr.wlr_cursor_warp_absolute(self.cursor, event.device, event.x, event.y); self.processCursorMotion(event.time_msec); } fn onCursorButton(self: *Server, event: *wlr.wlr_event_pointer_button) !void { wlr.wlr_idle_notify_activity(self.idle, self.seat); if (self.outputAtCursor()) |output| { if (output.spread_view) { var spread: SpreadParams = undefined; spread.set(self.toplevels, output); if (spread.cols == 0) return; const layout = output.getLayout(); const col = @divTrunc(@floatToInt(i32, self.cursor.x) - layout.x, spread.width); const row = @divTrunc(@floatToInt(i32, self.cursor.y) - layout.y, spread.height); var index = row * @intCast(i32, spread.cols) + col; var iter = self.toplevels.last; while (iter) |node| : ({ iter = node.prev; index -= 1; }) { if (index == 0) { self.toplevelToFront(node.data); break; } } output.toggleSpreadView(); return; } } self.processCursorMotion(event.time_msec); var handled = false; if (event.state == wlr.WLR_BUTTON_RELEASED) { if (self.cursor_mode != .passthrough) { self.cursor_mode = .passthrough; handled = true; self.grabbed_toplevel = null; } } else { const keyboard = wlr.wlr_seat_get_keyboard(self.seat); const modifiers = wlr.wlr_keyboard_get_modifiers(keyboard); if (modifiers == self.config.mouse_move_modifiers and event.button == self.config.mouse_move_button) { self.actionMove(); handled = true; } else if (modifiers == self.config.mouse_grow_modifiers and event.button == self.config.mouse_grow_button) { self.actionResize(); handled = true; } } if (!handled) { _ = wlr.wlr_seat_pointer_notify_button( self.seat, event.time_msec, event.button, event.state, ); } } fn onCursorAxis(self: *Server, event: *wlr.wlr_event_pointer_axis) !void { wlr.wlr_idle_notify_activity(self.idle, self.seat); self.processCursorMotion(event.time_msec); wlr.wlr_seat_pointer_notify_axis( self.seat, event.time_msec, event.orientation, event.delta, event.delta_discrete, event.source, ); } fn onCursorFrame(self: *Server, _: void) !void { wlr.wlr_seat_pointer_notify_frame(self.seat); } fn setKeyboardFocus(self: *Server, wlr_surface: *wlr.wlr_surface) void { if (Surface.fromWlrSurface(wlr_surface)) |next_surface| { if (!next_surface.shouldFocus()) { return; } if (self.seat.keyboard_state.focused_surface) |prev_wlr_surface| { if (prev_wlr_surface == wlr_surface) { return; } if (Surface.fromWlrSurface(prev_wlr_surface)) |prev_surface| { _ = prev_surface.setActivated(false); if (prev_surface != next_surface) { prev_surface.damageBorders(); } } } if (next_surface.setActivated(true)) { const wlr_keyboard: *wlr.wlr_keyboard = wlr.wlr_seat_get_keyboard(self.seat); wlr.wlr_seat_keyboard_notify_enter( self.seat, wlr_surface, &wlr_keyboard.keycodes, wlr_keyboard.num_keycodes, &wlr_keyboard.modifiers, ); } next_surface.damageBorders(); } } fn onNewInputDevice(self: *Server, device: *wlr.wlr_input_device) !void { switch (device.type) { wlr.WLR_INPUT_DEVICE_KEYBOARD => { _ = try Keyboard.create(self, device); }, wlr.WLR_INPUT_DEVICE_POINTER => { if (wlr.wlr_input_device_is_libinput(device)) { var libinput_device = wlr.wlr_libinput_get_device_handle(device); if (self.config.tap_to_click and wlr.libinput_device_config_tap_get_finger_count(libinput_device) != 0) { _ = wlr.libinput_device_config_tap_set_enabled( libinput_device, wlr.LIBINPUT_CONFIG_TAP_ENABLED, ); } if (wlr.libinput_device_config_scroll_has_natural_scroll(libinput_device) != 0) { _ = wlr.libinput_device_config_scroll_set_natural_scroll_enabled( libinput_device, if (self.config.natural_scrolling) 1 else 0, ); } } wlr.wlr_cursor_attach_input_device(self.cursor, device); }, else => {}, } var capabilities: u32 = wlr.WL_SEAT_CAPABILITY_POINTER; if (self.keyboards.first != null) capabilities |= wlr.WL_SEAT_CAPABILITY_KEYBOARD; wlr.wlr_seat_set_capabilities(self.seat, capabilities); } fn onRequestSetCursor(self: *Server, event: *wlr.wlr_seat_pointer_request_set_cursor_event) !void { if (self.seat.pointer_state.focused_client == event.seat_client) { wlr.wlr_cursor_set_surface(self.cursor, event.surface, event.hotspot_x, event.hotspot_y); } } fn onRequestSetSelection(self: *Server, event: *wlr.wlr_seat_request_set_selection_event) !void { wlr.wlr_seat_set_selection(self.seat, event.source, event.serial); } fn onRequestSetPrimarySelection( self: *Server, event: *wlr.wlr_seat_request_set_primary_selection_event, ) !void { wlr.wlr_seat_set_primary_selection(self.seat, event.source, event.serial); } fn onRequestStartDrag(self: *Server, event: *wlr.wlr_seat_request_start_drag_event) !void { if (wlr.wlr_seat_validate_pointer_grab_serial(self.seat, event.origin, event.serial)) { wlr.wlr_seat_start_pointer_drag(self.seat, event.drag, event.serial); } else { wlr.wlr_data_source_destroy(@ptrCast(*wlr.wlr_drag, event.drag).source); } } fn onStartDrag(self: *Server, wlr_drag: *wlr.wlr_drag) !void { self.drag_icon = try Surface.create(self, @ptrCast(*wlr.wlr_drag_icon, wlr_drag.icon), null); Signal.connect( void, self, "destroy_drag", Server.onDestroyDrag, &wlr_drag.events.destroy, ); } fn onDestroyDrag(self: *Server, _: void) !void { self.drag_icon = null; } fn onOutputManagerApply(self: *Server, config: *wlr.wlr_output_configuration_v1) !void { self.outputManagerApply(config, false); } fn onOutputManagerTest(self: *Server, config: *wlr.wlr_output_configuration_v1) !void { self.outputManagerApply(config, true); } fn outputManagerApply( self: *Server, config: *wlr.wlr_output_configuration_v1, is_test: bool, ) void { var test_passed = true; var iter: *wlr.wl_list = config.heads.next; while (iter != &config.heads) : (iter = iter.next) { const head = @fieldParentPtr(wlr.wlr_output_configuration_head_v1, "link", iter); wlr.wlr_output_enable(head.state.output, head.state.enabled); if (head.state.enabled) { if (head.state.mode) |mode| { wlr.wlr_output_set_mode(head.state.output, mode); } else { wlr.wlr_output_set_custom_mode( head.state.output, head.state.custom_mode.width, head.state.custom_mode.height, head.state.custom_mode.refresh, ); } wlr.wlr_output_layout_move( self.wlr_output_layout, head.state.output, head.state.x, head.state.y, ); wlr.wlr_output_set_transform(head.state.output, head.state.transform); wlr.wlr_output_set_scale(head.state.output, head.state.scale); } test_passed = wlr.wlr_output_test(head.state.output); if (!test_passed) { break; } } if (test_passed) { iter = config.heads.next; while (iter != &config.heads) : (iter = iter.next) { const head = @fieldParentPtr(wlr.wlr_output_configuration_head_v1, "link", iter); if (is_test) { wlr.wlr_output_rollback(head.state.output); } else { _ = wlr.wlr_output_commit(head.state.output); } } wlr.wlr_output_configuration_v1_send_succeeded(config); } else { wlr.wlr_output_configuration_v1_send_failed(config); } wlr.wlr_output_configuration_v1_destroy(config); self.configureCursor(); } fn onXwaylandReady(self: *Server, _: void) !void { if (self.xwayland) |xwayland| { var xc = wlr.xcb_connect(xwayland.display_name, null); const xc_err = wlr.xcb_connection_has_error(xc); if (xc_err != 0) { std.log.err("xcb_connect failed with code {d}", .{xc_err}); return; } wlr.wlr_xwayland_set_seat(xwayland, self.seat); if (wlr.wlr_xcursor_manager_get_xcursor(self.cursor_mgr, "left_ptr", 1)) |xcursor| { const img = @ptrCast( *wlr.wlr_xcursor_image, @ptrCast(*wlr.wlr_xcursor, xcursor).images[0], ); wlr.wlr_xwayland_set_cursor( xwayland, img.buffer, img.width * 4, img.width, img.height, @intCast(i32, img.hotspot_x), @intCast(i32, img.hotspot_y), ); } wlr.xcb_disconnect(xc); } } fn processCursorMove(self: *Server) void { if (self.grabbed_toplevel) |toplevel| { var box: wlr.wlr_box = undefined; toplevel.getGeometry(&box); box.x = @floatToInt(i32, self.cursor.x) - self.grab_x; box.y = @floatToInt(i32, self.cursor.y) - self.grab_y; toplevel.setGeometry(box); } } fn processCursorResize(self: *Server) void { if (self.grabbed_toplevel) |toplevel| { var border_x = @floatToInt(i32, self.cursor.x) - self.grab_x; var border_y = @floatToInt(i32, self.cursor.y) - self.grab_y; var new_position: wlr.wlr_box = undefined; new_position.x = self.grab_geobox.x; var new_right = self.grab_geobox.x + self.grab_geobox.width; new_position.y = self.grab_geobox.y; var new_bottom = self.grab_geobox.y + self.grab_geobox.height; if (self.resize_edges & wlr.WLR_EDGE_TOP != 0) { new_position.y = border_y; if (new_position.y >= new_bottom) { new_position.y = new_bottom - 1; } } else if (self.resize_edges & wlr.WLR_EDGE_BOTTOM != 0) { new_bottom = border_y; if (new_bottom <= new_position.y) { new_bottom = new_position.y + 1; } } if (self.resize_edges & wlr.WLR_EDGE_LEFT != 0) { new_position.x = border_x; if (new_position.x >= new_right) { new_position.x = new_right - 1; } } else if (self.resize_edges & wlr.WLR_EDGE_RIGHT != 0) { new_right = border_x; if (new_right <= new_position.x) { new_right = new_position.x + 1; } } new_position.width = new_right - new_position.x; new_position.height = new_bottom - new_position.y; toplevel.setGeometry(new_position); } } fn outputAt(self: *Server, x: f64, y: f64) ?*Output { return Output.fromWlrOutput(wlr.wlr_output_layout_output_at(self.wlr_output_layout, x, y)); } fn outputAtCursor(self: *Server) ?*Output { return self.outputAt(self.cursor.x, self.cursor.y); } fn processCursorMotion(self: *Server, time: u32) void { wlr.wlr_idle_notify_activity(self.idle, self.seat); if (self.cursor_mode == .move) { self.processCursorMove(); return; } else if (self.cursor_mode == .resize) { self.processCursorResize(); return; } if (self.outputAtCursor()) |output| { if (output.spread_view) return; var sx: f64 = undefined; var sy: f64 = undefined; var wlr_surface: ?*wlr.wlr_surface = null; wlr_surface = output.layerSurfaceAt( wlr.ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY, self.cursor.x, self.cursor.y, &sx, &sy, ); if (wlr_surface == null) { wlr_surface = output.layerSurfaceAt( wlr.ZWLR_LAYER_SHELL_V1_LAYER_TOP, self.cursor.x, self.cursor.y, &sx, &sy, ); } if (wlr_surface == null) { wlr_surface = self.toplevelAt(self.cursor.x, self.cursor.y, &sx, &sy); } if (wlr_surface == null) { wlr_surface = output.layerSurfaceAt( wlr.ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM, self.cursor.x, self.cursor.y, &sx, &sy, ); } if (wlr_surface == null) { wlr_surface = output.layerSurfaceAt( wlr.ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND, self.cursor.x, self.cursor.y, &sx, &sy, ); } if (wlr_surface) |surface_under_cursor| { self.setKeyboardFocus(surface_under_cursor); wlr.wlr_seat_pointer_notify_enter(self.seat, surface_under_cursor, sx, sy); wlr.wlr_seat_pointer_notify_motion(self.seat, time, sx, sy); } else { wlr.wlr_seat_pointer_clear_focus(self.seat); wlr.wlr_xcursor_manager_set_cursor_image(self.cursor_mgr, "left_ptr", self.cursor); var focused_surface = Surface.fromWlrSurface(self.seat.keyboard_state.focused_surface); if (focused_surface == null or !focused_surface.?.mapped) { var iter = self.toplevels.first; while (iter) |node| : (iter = node.next) { if (node.data.workspace == output.active_workspace) { node.data.setKeyboardFocus(); break; } } } } } } fn toplevelAt( self: *Server, x: f64, y: f64, sx: *f64, sy: *f64, ) ?*wlr.wlr_surface { if (self.outputAt(x, y)) |output| { for ([2]std.TailQueue(*Surface){ self.unmanaged_toplevels, self.toplevels, }) |list| { var iter = list.first; while (iter) |node| : (iter = node.next) { var toplevel = node.data; if (toplevel.workspace != output.active_workspace) { continue; } if (toplevel.surfaceAt(x, y, sx, sy)) |wlr_surface| { return wlr_surface; } } } } return null; } fn actionMove(self: *Server) void { self.grabToplevelForResizeMove(.move); } fn actionResize(self: *Server) void { self.grabToplevelForResizeMove(.resize); if (self.grabbed_toplevel) |toplevel| { toplevel.getGeometry(&self.grab_geobox); self.resize_edges = 0; var cursor_x = @floatToInt(i32, self.cursor.x); var cursor_y = @floatToInt(i32, self.cursor.y); if (cursor_x < self.grab_geobox.x + @divFloor(self.grab_geobox.width, 2)) { self.resize_edges |= wlr.WLR_EDGE_LEFT; } else { self.resize_edges |= wlr.WLR_EDGE_RIGHT; } if (cursor_y < self.grab_geobox.y + @divFloor(self.grab_geobox.height, 2)) { self.resize_edges |= wlr.WLR_EDGE_TOP; } else { self.resize_edges |= wlr.WLR_EDGE_BOTTOM; } var border_x = self.grab_geobox.x + (if ((self.resize_edges & wlr.WLR_EDGE_RIGHT) == 0) 0 else self.grab_geobox.width); var border_y = self.grab_geobox.y + (if ((self.resize_edges & wlr.WLR_EDGE_BOTTOM) == 0) 0 else self.grab_geobox.height); self.grab_x = cursor_x - border_x; self.grab_y = cursor_y - border_y; } } fn actionCmd(_: *Server, cmd: []const u8) void { const childProc = std.ChildProcess.init(&.{ "/bin/sh", "-c", cmd }, alloc) catch |err| { std.log.err("command failed: {s} {s}", .{ cmd, err }); return; }; childProc.spawn() catch |err| { std.log.err("command failed: {s} {s}", .{ cmd, err }); return; }; } fn grabToplevelForResizeMove(self: *Server, cursor_mode: CursorMode) void { if (self.getFocusedToplevel()) |toplevel| { if (!toplevel.is_actual_fullscreen) { var box: wlr.wlr_box = undefined; toplevel.getGeometry(&box); self.grabbed_toplevel = toplevel; self.cursor_mode = cursor_mode; self.grab_x = @floatToInt(i32, self.cursor.x) - box.x; self.grab_y = @floatToInt(i32, self.cursor.y) - box.y; } } } fn getFocusedToplevel(self: *Server) ?*Surface { if (Surface.fromWlrSurface(self.seat.keyboard_state.focused_surface)) |surface| { return surface.getToplevel(); } return null; } fn toplevelToFront(self: *Server, surface: *Surface) void { surface.setKeyboardFocus(); self.toplevels.remove(&surface.node); self.toplevels.prepend(&surface.node); surface.toFront(); self.damageAllOutputs(); } fn actionToplevelToFront(self: *Server, _: []const u8) void { if (self.getFocusedToplevel()) |toplevel| { self.toplevelToFront(toplevel); } } fn actionToplevelToBack(self: *Server, _: []const u8) void { if (self.getFocusedToplevel()) |toplevel| { self.toplevels.remove(&toplevel.node); self.toplevels.append(&toplevel.node); toplevel.toBack(); self.damageAllOutputs(); } } fn actionToplevelToWorkspace(self: *Server, arg: []const u8) void { if (self.getFocusedToplevel()) |toplevel| { const workspace = std.fmt.parseUnsigned(u32, arg, 10) catch return; toplevel.workspace = workspace; self.processCursorMotion(0); self.damageAllOutputs(); } } fn actionSwitchToWorkspace(self: *Server, arg: []const u8) void { if (self.outputAtCursor()) |output| { const workspace = std.fmt.parseUnsigned(u32, arg, 10) catch return; output.active_workspace = workspace; self.processCursorMotion(0); output.damageAll(); } } fn actionToggleSpreadView(self: *Server, _: []const u8) void { if (self.outputAtCursor()) |output| output.toggleSpreadView(); } fn actionToggleHideToplevels(self: *Server, _: []const u8) void { self.show_toplevels = !self.show_toplevels; self.damageAllOutputs(); } fn actionQuit(self: *Server, _: []const u8) void { wlr.wl_display_terminate(self.wl_display); } fn actionChvt(self: *Server, arg: []const u8) void { const vt = std.fmt.parseUnsigned(u32, arg, 10) catch return; _ = wlr.wlr_session_change_vt(wlr.wlr_backend_get_session(self.wlr_backend), vt); } fn ensureToplevelsVisible(self: *Server) void { var iter = self.toplevels.last; while (iter) |node| : (iter = node.prev) { if (!node.data.isVisible(true)) node.data.place(); } } fn nextIterCirc(list: std.TailQueue(*Surface), node: *std.TailQueue(*Surface).Node, forward: bool) ?*std.TailQueue(*Surface).Node { var iter = if (forward) node.next else node.prev; if (iter) |i| return i; return if (forward) list.first else list.last; } fn grabNextToplevel(self: *Server, forward: bool, app_id_comp: bool) void { if (if (self.grabbed_toplevel != null) self.grabbed_toplevel else self.getFocusedToplevel()) |start_toplevel| { var start_node = &start_toplevel.node; var iter = Server.nextIterCirc(self.toplevels, start_node, forward); while (iter) |node| : (iter = Server.nextIterCirc(self.toplevels, node, forward)) { if (node == start_node) { break; } if (!node.data.isVisible(false)) continue; if (std.mem.eql( u8, std.mem.span(node.data.getAppId()), std.mem.span(start_node.data.getAppId()), ) != app_id_comp) { continue; } self.grabbed_toplevel = node.data; self.damageAllOutputs(); break; } } } fn actionCycleToplevels(self: *Server, arg: []const u8) void { var forward = std.fmt.parseInt(i32, arg, 10) catch return; self.grabNextToplevel(forward > 0, true); } fn actionCycleGroups(self: *Server, arg: []const u8) void { var forward = std.fmt.parseInt(i32, arg, 10) catch return; self.grabNextToplevel(forward > 0, false); } fn reportHotkeyModifierState(self: *Server, pressed: bool) void { self.modifier_pressed = pressed; if (!pressed and self.cursor_mode == .passthrough) { if (self.grabbed_toplevel) |grabbed_toplevel| { self.grabbed_toplevel = null; self.toplevelToFront(grabbed_toplevel); } } } fn keyboardAdjustToplevel( self: *Server, arg: []const u8, comptime abscissa: []const u8, comptime ordinate: []const u8, ) void { if (self.getFocusedToplevel()) |toplevel| { if (std.meta.stringToEnum(Config.Direction, arg)) |dir| { toplevel.move(dir, self.config.move_pixels, abscissa, ordinate); } } } fn actionMoveKeyboard(self: *Server, arg: []const u8) void { self.keyboardAdjustToplevel(arg, "x", "y"); } fn actionGrowKeyboard(self: *Server, arg: []const u8) void { self.keyboardAdjustToplevel(arg, "width", "height"); } fn actionToggleFullscreen(self: *Server, _: []const u8) void { if (self.getFocusedToplevel()) |toplevel| { self.toplevelToFront(toplevel); toplevel.toggleFullscreen(); } } fn actionReloadConfig(self: *Server, _: []const u8) void { self.config.reload(); } fn damageAllOutputs(self: *Server) void { var iter = self.outputs.first; while (iter) |node| : (iter = node.next) { node.data.damageAll(); } } fn configureCursor(self: *Server) void { var iter = self.outputs.first; while (iter) |node| : (iter = node.next) { _ = wlr.wlr_xcursor_manager_load(self.cursor_mgr, node.data.wlr_output.scale); } } config: Config, wl_display: *wlr.wl_display, wlr_backend: *wlr.wlr_backend, wlr_renderer: *wlr.wlr_renderer, wlr_allocator: *wlr.wlr_allocator, toplevels: std.TailQueue(*Surface), unmanaged_toplevels: std.TailQueue(*Surface), show_toplevels: bool, wlr_output_layout: *wlr.wlr_output_layout, outputs: std.TailQueue(*Output), output_changed: wlr.wl_listener, new_output: wlr.wl_listener, output_manager: *wlr.wlr_output_manager_v1, output_manager_test: wlr.wl_listener, output_manager_apply: wlr.wl_listener, xdg_shell: *wlr.wlr_xdg_shell, new_xdg_surface: wlr.wl_listener, layer_shell: *wlr.wlr_layer_shell_v1, new_layer_surface: wlr.wl_listener, cursor: *wlr.wlr_cursor, cursor_mgr: *wlr.wlr_xcursor_manager, cursor_motion: wlr.wl_listener, cursor_motion_absolute: wlr.wl_listener, cursor_button: wlr.wl_listener, cursor_axis: wlr.wl_listener, cursor_frame: wlr.wl_listener, seat: *wlr.wlr_seat, new_input: wlr.wl_listener, request_cursor: wlr.wl_listener, request_set_selection: wlr.wl_listener, request_set_primary_selection: wlr.wl_listener, request_start_drag: wlr.wl_listener, start_drag: wlr.wl_listener, destroy_drag: wlr.wl_listener, drag_icon: ?*Surface, keyboards: std.TailQueue(*Keyboard), cursor_mode: CursorMode, grabbed_toplevel: ?*Surface, grab_geobox: wlr.wlr_box, grab_x: i32, grab_y: i32, resize_edges: u32, modifier_pressed: bool, input_inhibit_mgr: *wlr.wlr_input_inhibit_manager, idle: *wlr.wlr_idle, presentation: *wlr.wlr_presentation, new_xwayland_surface: wlr.wl_listener, xwayland_ready: wlr.wl_listener, xwayland: ?*wlr.wlr_xwayland, const CursorMode = enum { passthrough, move, resize, }; }; const Config = struct { const Action = enum { command, toplevel_to_front, toplevel_to_back, cycle_groups, cycle_toplevels, move_toplevel, grow_toplevel, toggle_fullscreen, toggle_spread_view, toggle_hide_toplevels, switch_to_workspace, toplevel_to_workspace, quit, chvt, reload_config, }; const Direction = enum { up, down, left, right, }; const DamageTrackingLevel = enum { minimal, partial, full, }; const KeyModifier = enum(u32) { shift = wlr.WLR_MODIFIER_SHIFT, caps = wlr.WLR_MODIFIER_CAPS, ctrl = wlr.WLR_MODIFIER_CTRL, alt = wlr.WLR_MODIFIER_ALT, mod2 = wlr.WLR_MODIFIER_MOD2, mod3 = wlr.WLR_MODIFIER_MOD3, logo = wlr.WLR_MODIFIER_LOGO, mod5 = wlr.WLR_MODIFIER_MOD5, }; const MouseButton = enum(u32) { left = wlr.BTN_LEFT, right = wlr.BTN_RIGHT, middle = wlr.BTN_MIDDLE, }; const Unparsed = struct { tap_to_click: ?bool = null, natural_scrolling: ?bool = null, background_color: ?[4]f32 = null, border_color: ?[4]f32 = null, focused_color: ?[4]f32 = null, grabbed_color: ?[4]f32 = null, active_border_width: ?i32 = null, hotkeys: ?[]struct { modifiers: []KeyModifier, key: []u8, action: Action, arg: []u8, } = null, mouse_move_modifiers: ?[]KeyModifier = null, mouse_move_button: ?MouseButton = null, mouse_grow_modifiers: ?[]KeyModifier = null, mouse_grow_button: ?MouseButton = null, autostart: ?[][]u8 = null, move_pixels: ?u32 = null, grow_pixels: ?u32 = null, damage_tracking: ?DamageTrackingLevel = null, }; fn loadDefault(self: *Config) void { const default = \\ { \\ "tap_to_click": true, \\ "natural_scrolling": true, \\ "background_color": [0.3, 0.3, 0.3, 1.0], \\ "border_color": [0.5, 0.5, 0.5, 1.0], \\ "focused_color": [0.28, 0.78, 1.0, 1.0], \\ "grabbed_color": [1.0, 0.6, 0.7, 1.0], \\ "active_border_width": 3, \\ "autostart": [], \\ "move_pixels": 10, \\ "grow_pixels": 10, \\ "damage_tracking": "minimal", \\ "mouse_move_modifiers": ["logo"], \\ "mouse_move_button": "left", \\ "mouse_grow_modifiers": ["logo", "shift"], \\ "mouse_grow_button": "left", \\ "hotkeys": [ \\ { \\ "modifiers": ["logo"], \\ "key": "t", \\ "action": "command", \\ "arg": "$TERM" \\ }, \\ { \\ "modifiers": ["ctrl", "alt"], \\ "key": "BackSpace", \\ "action": "quit", \\ "arg": "" \\ } \\ ] \\ } ; load(self, default); } fn loadFromFile(self: *Config) void { var path: ?[]const u8 = std.os.getenv("XDG_CONFIG_HOME"); if (path == null) { path = std.mem.concat( alloc, u8, &[2][]const u8{ std.os.getenv("HOME").?, "/.config" }, ) catch |err| { std.log.err("Could not read config: {s}", .{err}); return; }; } if (path) |cfgdir| { defer alloc.free(cfgdir); const cfgpath = std.mem.concat(alloc, u8, &.{ cfgdir, "/byway" }) catch |err| { std.log.err("Could not read config: {s}", .{err}); return; }; defer alloc.free(cfgpath); var byway_config_dir = std.fs.cwd().openDir(cfgpath, .{}) catch |err| { std.log.err("Could not read config: {s}", .{err}); return; }; defer byway_config_dir.close(); const contents = byway_config_dir.readFileAlloc( alloc, "config.json", 256000, ) catch |err| { std.log.err("Could not read config: {s}", .{err}); return; }; defer alloc.free(contents); load(self, contents); } } fn load(self: *Config, update: []const u8) void { var stream = std.json.TokenStream.init(update); @setEvalBranchQuota(10000); const parsed = std.json.parse(Unparsed, &stream, .{ .ignore_unknown_fields = true, .allocator = alloc, }) catch |err| { std.log.err("Could not parse config: {s}", .{err}); return; }; defer std.json.parseFree(Unparsed, parsed, .{ .allocator = alloc, }); if (parsed.mouse_grow_button) |mgb| self.mouse_grow_button = @enumToInt(mgb); if (parsed.mouse_grow_modifiers) |mgm| { self.mouse_grow_modifiers = 0; for (mgm) |mod| { self.mouse_grow_modifiers |= @enumToInt(mod); } } if (parsed.mouse_move_button) |mmb| self.mouse_move_button = @enumToInt(mmb); if (parsed.mouse_move_modifiers) |mmm| { self.mouse_move_modifiers = 0; for (mmm) |mod| { self.mouse_move_modifiers |= @enumToInt(mod); } } if (parsed.tap_to_click) |val| self.tap_to_click = val; if (parsed.natural_scrolling) |val| self.natural_scrolling = val; if (parsed.background_color) |val| self.background_color = val; if (parsed.border_color) |val| self.border_color = val; if (parsed.focused_color) |val| self.focused_color = val; if (parsed.grabbed_color) |val| self.grabbed_color = val; if (parsed.active_border_width) |val| self.active_border_width = val; if (parsed.move_pixels) |val| self.move_pixels = val; if (parsed.grow_pixels) |val| self.grow_pixels = val; if (parsed.damage_tracking) |val| self.damage_tracking = val; if (parsed.autostart) |autostart| { self.autostart.clearAndFree(); for (autostart) |cmdcfg| { var cmd = alloc.alloc(u8, cmdcfg.len) catch return; std.mem.copy(u8, cmd, cmdcfg); self.autostart.append(cmd) catch return; } } if (parsed.hotkeys) |hotkeys| { self.hotkeys = alloc.alloc(Hotkey, hotkeys.len) catch unreachable; for (hotkeys) |hotkeyConfig, idx| { self.hotkeys[idx].arg = alloc.alloc(u8, hotkeyConfig.arg.len) catch return; std.mem.copy(u8, self.hotkeys[idx].arg, hotkeyConfig.arg); self.hotkeys[idx].modifiers = 0; for (hotkeyConfig.modifiers) |mod| { self.hotkeys[idx].modifiers |= @enumToInt(mod); } var configKey = std.cstr.addNullByte(alloc, hotkeyConfig.key) catch return; defer alloc.free(configKey); self.hotkeys[idx].key = wlr.xkb_keysym_from_name(configKey, wlr.XKB_KEYSYM_NO_FLAGS); self.hotkeys[idx].cb = switch (hotkeyConfig.action) { .command => Server.actionCmd, .toplevel_to_front => Server.actionToplevelToFront, .toplevel_to_back => Server.actionToplevelToBack, .cycle_groups => Server.actionCycleGroups, .cycle_toplevels => Server.actionCycleToplevels, .move_toplevel => Server.actionMoveKeyboard, .grow_toplevel => Server.actionGrowKeyboard, .toggle_fullscreen => Server.actionToggleFullscreen, .switch_to_workspace => Server.actionSwitchToWorkspace, .toplevel_to_workspace => Server.actionToplevelToWorkspace, .toggle_spread_view => Server.actionToggleSpreadView, .toggle_hide_toplevels => Server.actionToggleHideToplevels, .quit => Server.actionQuit, .chvt => Server.actionChvt, .reload_config => Server.actionReloadConfig, }; } } } const Hotkey = struct { modifiers: u32, key: u32, cb: fn (*Server, []const u8) void, arg: []u8, }; tap_to_click: bool, natural_scrolling: bool, background_color: [4]f32, border_color: [4]f32, focused_color: [4]f32, grabbed_color: [4]f32, active_border_width: i32, hotkeys: []Hotkey, mouse_move_modifiers: u32, mouse_move_button: u32, mouse_grow_modifiers: u32, mouse_grow_button: u32, autostart: std.ArrayList([]u8), move_pixels: u32, grow_pixels: u32, damage_tracking: DamageTrackingLevel, fn init(self: *Config) void { self.autostart = std.ArrayList([]u8).init(alloc); self.loadDefault(); self.reload(); } fn reload(self: *Config) void { self.loadFromFile(); } }; const Signal = struct { fn connect( comptime PayloadType: type, container: anytype, comptime listenerField: []const u8, comptime cb: fn (container: @TypeOf(container), data: PayloadType) anyerror!void, signal: *wlr.wl_signal, ) void { var listener = &@field(container, listenerField); listener.notify = Listener(PayloadType, @TypeOf(container.*), listenerField, cb).onSignal; wlr.wl_signal_add(signal, listener); } fn Listener( comptime PayloadType: type, comptime ContainerType: type, comptime listenerField: []const u8, comptime cb: fn (container: *ContainerType, data: PayloadType) anyerror!void, ) type { return struct { fn onSignal(cbListener: [*c]wlr.wl_listener, data: ?*anyopaque) callconv(.C) void { cb( @fieldParentPtr(ContainerType, listenerField, cbListener), if (PayloadType == void) {} else @ptrCast( PayloadType, @alignCast(@alignOf(PayloadType), data), ), ) catch |err| { std.log.err("Error from callback {d}", .{err}); }; } }; } }; const wlr_xdg_surface_union = @typeInfo(wlr.wlr_xdg_surface).Struct.fields[5].name; const wlr_input_device_union = @typeInfo(wlr.wlr_input_device).Struct.fields[8].name; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var alloc = gpa.allocator();
src/main.zig
const std = @import("std"); const kernel = @import("kernel.zig"); const page_size = kernel.arch.page_size; const sector_size = kernel.arch.sector_size; pub const kb = 1024; pub const mb = kb * 1024; pub const gb = mb * 1024; pub const tb = gb * 1024; const log = kernel.log.scoped(.data_manipulation); pub inline fn string_eq(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } pub inline fn string_starts_with(str: []const u8, slice: []const u8) bool { return std.mem.startsWith(u8, str, slice); } pub inline fn string_ends_with(str: []const u8, slice: []const u8) bool { return std.mem.endsWith(u8, str, slice); } pub inline fn align_forward(n: u64, alignment: u64) u64 { const mask: u64 = alignment - 1; const result = (n + mask) & ~mask; return result; } pub inline fn align_backward(n: u64, alignment: u64) u64 { return n & ~(alignment - 1); } pub inline fn is_aligned(n: u64, alignment: u64) bool { return n & (alignment - 1) == 0; } pub inline fn read_int_big(comptime T: type, slice: []const u8) T { return std.mem.readIntBig(T, slice[0..@sizeOf(T)]); } pub const copy = std.mem.copy; pub inline fn zero_typed_address(address: u64, comptime T: type) *T { const result = @intToPtr(*T, address); result.* = zeroes(T); return result; } pub inline fn zero_range(address: u64, size: u64) void { zero(@intToPtr([*]u8, address)[0..size]); } pub inline fn zero(bytes: []u8) void { for (bytes) |*byte| byte.* = 0; } pub inline fn zero_slice(slice: anytype) void { const bytes = as_bytes(slice); zero(bytes); } pub inline fn zeroes(comptime T: type) T { var result: T = undefined; zero(@ptrCast([*]u8, &result)[0..@sizeOf(T)]); return result; } pub inline fn zero_a_page(page_address: u64) void { kernel.assert(@src(), is_aligned(page_address, kernel.arch.page_size)); zero(@intToPtr([*]u8, page_address)[0..kernel.arch.page_size]); } pub inline fn bytes_to_pages(bytes: u64, comptime must_be_exact: bool) u64 { return remainder_division_maybe_exact(bytes, page_size, must_be_exact); } pub inline fn bytes_to_sector(bytes: u64, comptime must_be_exact: bool) u64 { return remainder_division_maybe_exact(bytes, sector_size, must_be_exact); } pub inline fn remainder_division_maybe_exact(dividend: u64, divisor: u64, comptime must_be_exact: bool) u64 { if (divisor == 0) unreachable; const quotient = dividend / divisor; const remainder = dividend % divisor; const remainder_not_zero = remainder != 0; if (must_be_exact and remainder_not_zero) kernel.panic("remainder not exact when asked to be exact: {} / {}", .{ dividend, divisor }); return quotient + @boolToInt(remainder_not_zero); } pub const maxInt = std.math.maxInt; pub const as_bytes = std.mem.asBytes; pub const spinloop_hint = std.atomic.spinLoopHint; pub fn cstr_len(cstr: [*:0]const u8) u64 { var length: u64 = 0; while (cstr[length] != 0) : (length += 1) {} return length; } pub const enum_values = std.enums.values; pub const IntType = std.meta.Int; pub fn Bitflag(comptime is_volatile: bool, comptime EnumT: type) type { return struct { pub const Enum = EnumT; const BitFlagIntType = std.meta.Int(.unsigned, @bitSizeOf(EnumT)); const Ptr = if (is_volatile) *volatile @This() else *@This(); bits: BitFlagIntType, pub inline fn from_flags(comptime flags: []const EnumT) @This() { const result = comptime blk: { if (flags.len > @bitSizeOf(EnumT)) @compileError("More flags than bits\n"); comptime var bits: BitFlagIntType = 0; inline for (flags) |field| { bits |= 1 << @enumToInt(field); } break :blk bits; }; return @This(){ .bits = result }; } //pub inline fn from_flags(flags: []EnumT) @This() { //const flags_type = @TypeOf(flags); //const result = comptime blk: { //const flag_fields = std.meta.fields(flags_type); //if (flag_fields.len > @bitSizeOf(EnumT)) @compileError("More flags than bits\n"); //var bits: BitFlagIntType = 0; //inline for (flag_fields) |flag_field| { //const enum_value: EnumT = @ptrCast(*const EnumT, flag_field.default_value.?).*; //bits |= 1 << @enumToInt(enum_value); //} //break :blk bits; //}; //return @This(){ .bits = result }; //} pub fn from_bits(bits: BitFlagIntType) @This() { return @This(){ .bits = bits }; } pub inline fn from_flag(comptime flag: EnumT) @This() { const bits = 1 << @enumToInt(flag); return @This(){ .bits = bits }; } pub inline fn empty() @This() { return @This(){ .bits = 0, }; } pub inline fn all() @This() { var result = comptime blk: { var bits: BitFlagIntType = 0; inline for (@typeInfo(EnumT).Enum.fields) |field| { bits |= 1 << field.value; } break :blk @This(){ .bits = bits, }; }; return result; } pub inline fn is_empty(self: @This()) bool { return self.bits == 0; } /// This assumes invalid values in the flags can't be set. pub inline fn is_all(self: @This()) bool { return all().bits == self.bits; } pub inline fn contains(self: @This(), comptime flag: EnumT) bool { return ((self.bits & (1 << @enumToInt(flag))) >> @enumToInt(flag)) != 0; } // TODO: create a mutable version of this pub inline fn or_flag(self: Ptr, comptime flag: EnumT) void { self.bits |= 1 << @enumToInt(flag); } pub fn format(bitflag: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void { try writer.writeAll("{\n"); for (enum_values(Enum)) |enum_value| { const bit_value = @boolToInt(bitflag.bits & (@as(BitFlagIntType, 1) << @intCast(u6, @enumToInt(enum_value))) != 0); try std.fmt.format(writer, "\t{s}: {}\n", .{ @tagName(enum_value), bit_value }); } try writer.writeAll("}"); } }; } pub const fields = std.meta.fields;
src/kernel/data_manipulation.zig
const std = @import("std"); const util = @import("util.zig"); /// A game ROM, with memory mapping based on LoROM. pub const ROM = struct { bytes: []const u8, /// Load the ROM from a file, allocating memory with a given allocator. pub fn init(allocator: *std.mem.Allocator, filename: []const u8) !ROM { const file = try std.fs.cwd().openFile(filename, .{}); defer file.close(); const size = (try file.stat()).size; // account for SMC header const offset = @intCast(u10, size & 0x3FF); if (offset != 0 and offset != 512) { return error.InvalidHeader; } const rom_size = size - offset; if (rom_size < 0x1000) { return error.ROMTooSmall; } else if (rom_size > 0x3FFFFF) { return error.ROMTooLarge; } const bytes = try allocator.alloc(u8, @intCast(u22, rom_size)); errdefer allocator.free(bytes); // do some header validation so we have at least some belief that this is correct data const expected_size = std.math.log2_int(u12, @intCast(u12, @intCast(u22, rom_size) >> 10)); // we're only checking the LoROM area try file.seekTo(@as(u16, offset) + 0x7FD7); if (expected_size != try file.reader().readByte()) { return error.InvalidHeader; } // lgtm, read the file try file.seekTo(offset); try file.reader().readNoEof(bytes); return ROM{ .bytes = bytes }; } /// Release this ROM's memory, using the same allocator it was created with. pub fn deinit(self: ROM, allocator: *std.mem.Allocator) void { allocator.free(self.bytes); } /// Create a readable stream view into a ROM. pub fn view(self: ROM, pos: u24) ROMView { return ROMView{ .data = self.bytes, .pos = pos }; } }; /// A view of a ROM mapped to a 24-bit address space via LoROM. Access of memory not mapped to ROM is not allowed. pub const ROMView = struct { data: []const u8, pos: u24, fn mapAddress(self: ROMView) !u24 { const offset = @truncate(u16, self.pos); // ROM is never mapped to the lower half of a bank, afaik if (offset < 0x8000) { return error.NotMappedToROM; } const bank = switch (@intCast(u8, self.pos >> 16)) { 0x00...0x3F => |b| b, 0x40...0x5F => |b| b ^ 0x40, 0x80...0xBF => |b| b ^ 0x80, else => return error.NotMappedToROM, }; // based on similar bsnes and snes9x code var size = @intCast(u24, self.data.len); std.debug.assert(size != 0); var addr = (offset & 0x7FFF) | (@as(u24, bank) << 15); var base: u24 = 0; var mask: u24 = 1 << 23; while (addr >= size) { while ((addr & mask) == 0) { mask >>= 1; } addr &= ~mask; if (size > mask) { size &= ~mask; base |= mask; } } return base | addr; } /// Read bytes from the ROM. fn read(self: *ROMView, buf: []u8) !usize { // TODO calculate only the start address and ensure the read will not enter unmapped areas for (buf) |*b| { b.* = self.data[try self.mapAddress()]; self.pos +%= 1; } return buf.len; } pub usingnamespace util.AutoReader(read); };
src/rom.zig
const std = @import("std"); const GL = @import("../util/opengl.zig"); const Ring = @import("../util/ring.zig"); const shared = @import("../shared.zig"); const zigimg = @import("zigimg"); const UI = @import("../util/ui.zig"); const GLRenderer = @import("../gl_renderer.zig"); const Editor = @import("../editor.zig"); usingnamespace std.os.windows; const ProcedureData = struct { var wndproc_atom_ptr: ?LPCSTR = null; msg_queue: *MessageQueue, old_wnd_proc: LONG_PTR, }; const Message = union(enum) { MouseMove: UI.MousePos, MouseDown: void, MouseUp: void, KeyDown: usize, KeyUp: usize, }; const DraggingInfo = struct { start: UI.MousePos, current: UI.MousePos, ui_id: u32, }; const MessageQueue = std.fifo.LinearFifo(Message, .Dynamic); pub const Renderer = struct { allocator: *std.mem.Allocator, thread: ?*std.Thread = null, should_close: bool = false, ring: Ring, images: ?GLRenderer.Images = null, editor: *Editor, msg_queue: MessageQueue, pub fn init(allocator: *std.mem.Allocator, editor: *Editor) !Renderer { return Renderer{ .allocator = allocator, .ring = try Ring.init(allocator, 65536), .msg_queue = MessageQueue.init(allocator), .editor = editor, }; } pub fn editorOpen(self: *Renderer, ptr: *c_void) !void { const hwnd = @ptrCast(HWND, ptr); self.thread = try std.Thread.spawn(renderLoop, .{ .self = self, .hwnd = hwnd, }); } pub fn editorClose(self: *Renderer) void { if (self.thread) |thread| { self.should_close = true; thread.wait(); self.thread = null; self.should_close = false; } } pub fn update(self: *Renderer, buffer: []f32) void { self.ring.write(buffer); } const RenderArgs = struct { self: *Renderer, hwnd: HWND, }; fn renderLoop(args: RenderArgs) !void { const self = args.self; const hwnd = args.hwnd; var proc_data = ProcedureData{ .msg_queue = &self.msg_queue, .old_wnd_proc = GetWindowLongPtrA(hwnd, GWLP_WNDPROC), }; if (ProcedureData.wndproc_atom_ptr == null) { const atom = GlobalAddAtomA("zig-analyzer-wndproc-storage"); // High word needs to be all 0 and the low word needs to be the atom identifier. const atom_ptr_int = @as(usize, atom & 0xffff); ProcedureData.wndproc_atom_ptr = @intToPtr([*:0]const CHAR, atom_ptr_int); } if (SetPropA(hwnd, ProcedureData.wndproc_atom_ptr.?, @ptrCast(*c_void, &proc_data)) != TRUE) { std.log.crit("SetPropA failed", .{}); } const proc_ptr = @intCast(isize, @ptrToInt(customWindowProcedure)); if (SetWindowLongPtrA(hwnd, GWLP_WNDPROC, proc_ptr) == 0) { std.log.crit("Failed to set the custom window procedure: {}", .{GetLastError()}); } defer { if (SetWindowLongPtrA(hwnd, GWLP_WNDPROC, proc_data.old_wnd_proc) == 0) { std.log.debug("Failed to reset the window procedure: {}", .{GetLastError()}); } } var instance = try wglSetup(self.allocator, hwnd); defer instance.deinit(); _ = instance.makeCurrent(); var opengl = try instance.loadFunctions(); self.images = self.images orelse try self.loadImages(); var gl_renderer = try GLRenderer.init(self.allocator, &opengl, &self.ring, self.images.?); defer gl_renderer.deinit(); const viewport = GLRenderer.Viewport{ .width = 900, .height = 900 }; gl_renderer.resize(viewport); const time_ms = 800; const frame_count = 48_000 * (time_ms / @as(f64, 1000.0)); gl_renderer.gpu_ring.resize(@floatToInt(usize, frame_count) * 2); var mouse_pos: UI.MousePos = .{ .x = 0, .y = 0 }; var mouse_down: bool = false; var dragging: ?DraggingInfo = null; while (!self.should_close) { var mouse_moved_this_frame = false; var mouse_down_this_frame = false; while (self.msg_queue.readItem()) |msg| switch (msg) { .KeyDown => |code| switch (code) { 84 => { const mode = self.editor.lissajous_mode; const mode_int = @enumToInt(mode); var new_int = mode_int + 1; if (new_int >= comptime std.meta.fields(Editor.LissajousMode).len) { new_int = 0; } self.editor.lissajous_mode = @intToEnum(Editor.LissajousMode, new_int); }, else => {}, }, .MouseMove => |move_pos| { mouse_pos = move_pos; mouse_moved_this_frame = true; }, .MouseDown => { mouse_down = true; mouse_down_this_frame = true; }, .MouseUp => { mouse_down = false; dragging = null; }, else => {}, }; const picked_id = gl_renderer.render(self.editor.*, viewport, mouse_pos); if (dragging) |*drag_info| { drag_info.current = mouse_pos; std.log.debug("{}", .{drag_info}); } else if (mouse_down and mouse_moved_this_frame and picked_id != null) { dragging = DraggingInfo{ .start = mouse_pos, .current = mouse_pos, .ui_id = picked_id.?, }; } else if (mouse_down_this_frame and picked_id != null) { std.log.debug("Clicked {}", .{picked_id.?}); } _ = instance.swapBuffers(); } std.log.debug("Cleanup", .{}); } fn loadImages(self: *Renderer) !GLRenderer.Images { var img = try zigimg.Image.fromMemory(self.allocator, @embedFile("../../resources/scale.png")); var pixels = img.pixels orelse return error.ImageNoPixels; var buffer = try self.allocator.alloc(u8, pixels.len() * 4); var it = img.iterator(); var i: usize = 0; while (it.next()) |value| { buffer[i] = @floatToInt(u8, std.math.floor(value.R * 255)); buffer[i + 1] = @floatToInt(u8, std.math.floor(value.G * 255)); buffer[i + 2] = @floatToInt(u8, std.math.floor(value.B * 255)); buffer[i + 3] = @floatToInt(u8, std.math.floor(value.A * 255)); i += 4; } return GLRenderer.Images{ .scale = buffer, }; } }; fn customWindowProcedure(hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) LRESULT { var proc_data = getProcDataProp(hwnd); var msg_queue = proc_data.msg_queue; switch (msg) { 0x100 => { msg_queue.writeItem(.{ .KeyDown = wparam }) catch unreachable; }, 0x101 => { msg_queue.writeItem(.{ .KeyUp = wparam }) catch unreachable; }, 512 => { const lo = @bitCast(i16, @intCast(u16, lparam & 0xffff)); const hi = @bitCast(i16, @intCast(u16, (lparam >> 16) & 0xffff)); const mouse_pos = UI.MousePos{ .x = lo, .y = hi }; msg_queue.writeItem(.{ .MouseMove = mouse_pos }) catch unreachable; }, 513 => { msg_queue.writeItem(.{ .MouseDown = {} }) catch unreachable; }, 514 => { msg_queue.writeItem(.{ .MouseUp = {} }) catch unreachable; }, else => {}, } const old_proc = @intToPtr(WNDPROC, @intCast(usize, proc_data.old_wnd_proc)); return CallWindowProcA(old_proc, hwnd, msg, wparam, lparam); } fn getProcDataProp(hwnd: HWND) *ProcedureData { const handle = GetPropA(hwnd, ProcedureData.wndproc_atom_ptr.?); const aligned_ptr = @alignCast(@alignOf(ProcedureData), handle); return @ptrCast(*ProcedureData, aligned_ptr); } extern "user32" fn GetDC(hwnd: HWND) HDC; extern "user32" fn GetWindowLongPtrA(HWND, c_int) LONG_PTR; extern "user32" fn CallWindowProcA(WNDPROC, HWND, UINT, WPARAM, LPARAM) LRESULT; extern "user32" fn SetWindowLongPtrA(HWND, c_int, LONG_PTR) LONG_PTR; extern "user32" fn GlobalAddAtomA(LPCSTR) ATOM; extern "user32" fn SetPropA(HWND, LPCSTR, HANDLE) BOOL; extern "user32" fn GetPropA(HWND, LPCSTR) HANDLE; extern "gdi32" fn ChoosePixelFormat(hdc: HDC, ppfd: *const PixelFormatDescriptor) c_int; extern "gdi32" fn SetPixelFormat(hdc: HDC, format: c_int, ppfd: *const PixelFormatDescriptor) BOOL; extern "opengl32" fn wglCreateContext(hdc: HDC) ?HGLRC; extern "opengl32" fn wglDeleteContext(HGLRC) BOOL; extern "opengl32" fn wglMakeCurrent(hdc: HDC, glrc: ?HGLRC) BOOL; extern "opengl32" fn wglGetProcAddress(name: LPCSTR) ?*c_void; extern "opengl32" fn SwapBuffers(hdc: HDC) BOOL; extern fn SetLastError(DWORD) void; extern fn GetLastError() DWORD; const WNDPROC = fn (hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) callconv(.C) LRESULT; const GWLP_WNDPROC = -4; const PixelFormatDescriptor = extern struct { Size: WORD, Version: WORD, wFlags: DWORD, PixelType: BYTE, ColorBits: BYTE, RedBits: BYTE, RedShift: BYTE, GreenBits: BYTE, GreenShift: BYTE, BlueBits: BYTE, BlueShift: BYTE, AlphaBits: BYTE, AlphaShift: BYTE, AccumBits: BYTE, AccumRedBits: BYTE, AccumGreenBits: BYTE, AccumBlueBits: BYTE, AccumAlphaBits: BYTE, DepthBits: BYTE, StencilBits: BYTE, AuxBuffers: BYTE, LayerType: BYTE, Reserved: BYTE, wLayerMask: DWORD, wVisibleMask: DWORD, wDamageMask: DWORD, }; const PFD_DRAW_TO_WINDOW: DWORD = 4; const PFD_SUPPORT_OPENGL: DWORD = 32; const PFD_DOUBLEBUFFER: DWORD = 1; const PFD_TYPE_RGBA: DWORD = 0; const PFD_MAIN_PLANE: DWORD = 1; const WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091; const WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092; const WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126; const WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001; fn wglSetup(allocator: *std.mem.Allocator, hwnd: HWND) !Instance { const pfd = PixelFormatDescriptor{ .Size = @sizeOf(PixelFormatDescriptor), .Version = 1, .wFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, .PixelType = PFD_TYPE_RGBA, .ColorBits = 32, .RedBits = 0, .RedShift = 0, .GreenBits = 0, .GreenShift = 0, .BlueBits = 0, .BlueShift = 0, .AlphaBits = 0, .AlphaShift = 0, .AccumBits = 0, .AccumRedBits = 0, .AccumGreenBits = 0, .AccumBlueBits = 0, .AccumAlphaBits = 0, .DepthBits = 24, .StencilBits = 8, .AuxBuffers = 0, .LayerType = PFD_MAIN_PLANE, .Reserved = 0, .wLayerMask = 0, .wVisibleMask = 0, .wDamageMask = 0, }; const hdc = GetDC(hwnd); const pixel_format = ChoosePixelFormat(hdc, &pfd); if (pixel_format == 0) { return error.PixelFormatIsZero; } if (SetPixelFormat(hdc, pixel_format, &pfd) == FALSE) { return error.SetPixelFormatFailed; } var gl_lib = try std.DynLib.open("opengl32.dll"); const gl_ctx = wglCreateContext(hdc) orelse return error.wglCreateContextFailed; defer std.debug.assert(wglDeleteContext(gl_ctx) == TRUE); if (wglMakeCurrent(hdc, gl_ctx) == FALSE) return error.wglMakeCurrentFailed; const wglCreateContextAttribsARB = getOpenGLProc(fn (HDC, ?HGLRC, ?[*:0]const i32) ?HGLRC, "wglCreateContextAttribsARB").?; _ = setupSwapInterval(&gl_lib, hdc); const attribs = [_]i32{ WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, } ++ [_]i32{0}; const c_attribs = @ptrCast([*:0]const i32, &attribs); const modern_ctx = wglCreateContextAttribsARB(hdc, null, c_attribs) orelse return error.CreateContextARBNull; if (wglMakeCurrent(hdc, modern_ctx) == FALSE) return error.wglMakeModernCurrentFailed; return Instance{ .allocator = allocator, .hdc = hdc, .ctx = modern_ctx, .dynlib = gl_lib, }; } fn setupSwapInterval(gl_lib: *std.DynLib, hdc: HDC) bool { const glGetString = gl_lib.lookup(fn (GL.Enum) [*:0]GL.char, "glGetString").?; const wglGetExtensionsStringARB = getOpenGLProc(fn (HDC) [*:0]u8, "wglGetExtensionsStringARB").?; const extensions = std.mem.span(glGetString(GL.EXTENSIONS)); const wgl_extensions = std.mem.span(wglGetExtensionsStringARB(hdc)); const ext_supported = std.mem.indexOf(u8, extensions, "WGL_EXT_swap_control") != null; const wgl_ext_supported = std.mem.indexOf(u8, wgl_extensions, "WGL_EXT_swap_control") != null; if (ext_supported and wgl_ext_supported) { const wglSwapIntervalEXT = getOpenGLProc(fn (c_int) BOOL, "wglSwapIntervalEXT").?; return wglSwapIntervalEXT(1) == TRUE; } return false; } fn getOpenGLProc(comptime T: type, name: [*:0]const u8) ?T { const ptr = wglGetProcAddress(name) orelse return null; return @ptrCast(T, ptr); } const Instance = struct { allocator: *std.mem.Allocator, dynlib: std.DynLib, hdc: HDC, ctx: HGLRC, pub fn deinit(self: *Instance) void { self.dynlib.close(); if (wglDeleteContext(self.ctx) != TRUE) std.log.crit("wglDeleteContext failed", .{}); } pub fn makeCurrent(self: *Instance) bool { return wglMakeCurrent(self.hdc, self.ctx) == TRUE; } pub fn swapBuffers(self: *Instance) bool { return SwapBuffers(self.hdc) == TRUE; } pub fn loadFunctions(self: *Instance) !GL { var gl: GL = undefined; var success: bool = true; inline for (std.meta.fields(GL)) |field| { const info = @typeInfo(field.field_type); switch (info) { .Fn => { var buf = try self.allocator.allocSentinel(u8, field.name.len, 0); defer self.allocator.free(buf); std.mem.copy(u8, buf, field.name); buf[buf.len] = 0; if (getOpenGLProc(field.field_type, buf)) |fn_ptr| { @field(gl, field.name) = fn_ptr; } else if (self.dynlib.lookup(field.field_type, buf)) |fn_ptr| { @field(gl, field.name) = fn_ptr; } else { std.log.crit("Unable to get a valid pointer for '{s}'", .{field.name}); success = false; } }, else => {}, } } return if (success) gl else error.UnableToGetAllFunctions; } };
src/windows/gl_wrapper.zig
const std = @import("std"); const stdx = @import("stdx"); const ui = @import("../ui.zig"); const log = stdx.log.scoped(.containers); /// Provides padding around a child widget. pub const Padding = struct { props: struct { pad_top: ?f32 = null, pad_right: ?f32 = null, pad_bottom: ?f32 = null, pad_left: ?f32 = null, padding: f32 = 10, child: ui.FrameId = ui.NullFrameId, }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = self; _ = c; return self.props.child; } pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { _ = self; var pad_top = self.props.pad_top orelse self.props.padding; var pad_right = self.props.pad_right orelse self.props.padding; var pad_bottom = self.props.pad_bottom orelse self.props.padding; var pad_left = self.props.pad_left orelse self.props.padding; const h_pad = pad_left + pad_right; const v_pad = pad_top + pad_bottom; const cstr = c.getSizeConstraint(); const node = c.getNode(); if (node.children.items.len == 0) { return ui.LayoutSize.init(h_pad, v_pad); } const child = node.children.items[0]; if (!c.prefer_exact_width_or_height) { var child_size = c.computeLayout(child, cstr); c.setLayout(child, ui.Layout.init(pad_left, pad_top, child_size.width, child_size.height)); return child_size.toIncSize(h_pad, v_pad); } else { const child_cstr = cstr.toIncSize(-h_pad, -v_pad); const child_size = c.computeLayoutStretch(child, child_cstr, c.prefer_exact_width, c.prefer_exact_height); c.setLayout(child, ui.Layout.init(pad_left, pad_top, child_size.width, child_size.height)); return child_size.toIncSize(h_pad, v_pad); } } }; pub const Sized = struct { props: struct { /// If width is not provided, this container will shrink to the child's width. width: ?f32 = null, /// If height is not provided, this container will shrink to the child's height. height: ?f32 = null, child: ui.FrameId = ui.NullFrameId, }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = c; return self.props.child; } pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { if (self.props.child != ui.NullFrameId) { var child_cstr = c.getSizeConstraint(); var prefer_exact_width = c.prefer_exact_width; var prefer_exact_height = c.prefer_exact_height; if (self.props.width) |width| { child_cstr.width = width; prefer_exact_width = true; } if (self.props.height) |height| { child_cstr.height = height; prefer_exact_height = true; } const child = c.getNode().children.items[0]; const child_size = c.computeLayoutStretch(child, child_cstr, prefer_exact_width, prefer_exact_height); c.setLayout(child, ui.Layout.init(0, 0, child_size.width, child_size.height)); var res = ui.LayoutSize.init(0, 0); res.width = self.props.width orelse child_size.width; res.height = self.props.height orelse child_size.height; return res; } else { var res = ui.LayoutSize.init(0, 0); res.width = self.props.width orelse 0; res.height = self.props.height orelse 0; return res; } } }; pub const Center = struct { props: struct { child: ui.FrameId = ui.NullFrameId, vcenter: bool = true, hcenter: bool = true, }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = c; return self.props.child; } pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { const cstr = c.getSizeConstraint(); if (self.props.child == ui.NullFrameId) { return cstr; } const node = c.getNode(); const child = node.children.items[0]; var child_size = c.computeLayout(child, cstr); child_size.cropTo(cstr); const x = if (self.props.hcenter) (cstr.width - child_size.width)/2 else 0; const y = if (self.props.vcenter) (cstr.height - child_size.height)/2 else 0; c.setLayout(child, ui.Layout.init(x, y, child_size.width, child_size.height)); return cstr; } }; const StretchMethod = enum(u3) { None = 0, Both = 1, Width = 2, Height = 3, WidthAndKeepRatio = 4, HeightAndKeepRatio = 5, }; /// When method = WidthAndKeepRatio, the width is stretched and the height is adjusted to keep the aspect ratio. /// When method = HeightAndKeepRatio, the height is stretched and the width is adjusted to keep the aspect ratio. pub const Stretch = struct { props: struct { child: ui.FrameId = ui.NullFrameId, method: StretchMethod = .Both, /// Width to height ratio. aspect_ratio: f32 = 1, }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = c; return self.props.child; } pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { var cstr = c.getSizeConstraint(); switch (self.props.method) { .WidthAndKeepRatio => cstr.height = cstr.width / self.props.aspect_ratio, .HeightAndKeepRatio => cstr.width = cstr.height * self.props.aspect_ratio, else => {}, } if (self.props.child == ui.NullFrameId) { return cstr; } const h_stretch = self.props.method == .Both or self.props.method == .Width or self.props.method == .WidthAndKeepRatio or self.props.method == .HeightAndKeepRatio; const v_stretch = self.props.method == .Both or self.props.method == .Height or self.props.method == .WidthAndKeepRatio or self.props.method == .HeightAndKeepRatio; const node = c.getNode(); const child = node.children.items[0]; var child_size = c.computeLayoutStretch(child, cstr, h_stretch, v_stretch); child_size.cropTo(cstr); c.setLayout(child, ui.Layout.init(0, 0, child_size.width, child_size.height)); var res = child_size; if (h_stretch) { res.width = cstr.width; } if (v_stretch) { res.height = cstr.height; } return res; } }; // TODO: Children can override the order by providing a z-index property. All children default to 0 z-index which results in the natural order. // A higher z-index would raise the child up. /// Stacks children over each other. The first child will be rendered last and receive input events last. pub const ZStack = struct { props: struct { children: ui.FrameListPtr = ui.FrameListPtr.init(0, 0), }, /// Ordered by z-index asc. ordered_children: std.ArrayList(u32), /// Ordered by z-index desc. child_event_ordering: std.ArrayList(*ui.Node), const Self = @This(); pub fn init(self: *Self, c: *ui.InitContext) void { self.ordered_children = std.ArrayList(u32).init(c.alloc); self.child_event_ordering = std.ArrayList(*ui.Node).init(c.alloc); } pub fn deinit(node: *ui.Node, _: std.mem.Allocator) void { const self = node.getWidget(Self); self.ordered_children.deinit(); self.child_event_ordering.deinit(); } pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { // Ordering is determined at build step. self.ordered_children.ensureTotalCapacity(self.props.children.len) catch @panic("error"); self.ordered_children.items.len = 0; // For now, the order is the same. var i: u32 = 0; while (i < self.props.children.len) : (i += 1) { self.ordered_children.appendAssumeCapacity(i); } return c.fragment(self.props.children); } pub fn postUpdate(node: *ui.Node) void { const self = node.getWidget(Self); // Child event ordering is z-index desc. self.child_event_ordering.ensureTotalCapacity(self.props.children.len) catch @panic("error"); self.child_event_ordering.items.len = 0; var i = @intCast(u32, self.props.children.len); while (i > 0) { i -= 1; self.child_event_ordering.appendAssumeCapacity(node.children.items[i]); } node.setChildEventOrdering(self.child_event_ordering.items); } /// Return ordering sorted by z-index desc. pub fn childEventOrdering(self: *Self) []const u32 { return self.child_event_ordering.items; } pub fn renderCustom(self: *Self, c: *ui.RenderContext) void { const node = c.node; // Rendered by z-index asc. for (self.ordered_children.items) |idx| { const child = node.children.items[idx]; c.renderChildNode(node, child); } } }; // TODO: Container with more comprehensive properties. // pub const Container = struct { // const Self = @This(); // };
ui/src/widgets/containers.zig
const std = @import("std"); const Record = @import("lsmtree").Record; const RecordError = @import("lsmtree").RecordError; const KeyLengthType = @import("lsmtree").KeyLengthType; const RecordLengthType = @import("lsmtree").RecordLengthType; const Op = @import("lsmtree").Op; const lsmtree = @import("lsmtree"); const expect = std.testing.expect; const expectEq = std.testing.expectEqual; /// TODO Update comment. Writes into the provided buf the data of the record in a contiguous array as described /// in fn Record() pub fn toBytes(record: *Record, buf: []u8) RecordError!usize { var offset: usize = 0; //Abort early if necessary if (buf.len < record.record_size_in_bytes) { return RecordError.BufferTooSmall; } if (record.key.len > std.math.maxInt(KeyLengthType)) { return RecordError.KeyTooBig; } buf[0] = @enumToInt(record.op); offset += 1; // Write N bytes to indicate the total size of the record. N is defined as the number of bytes // that a type RecordLengthType can store (8 for u64, 4 for a u32, etc.) std.mem.writeIntSliceLittle(RecordLengthType, buf[offset .. offset + @sizeOf(RecordLengthType)], record.record_size_in_bytes); offset += @sizeOf(RecordLengthType); // We can truncate here because we have already checked that the size will fit above const temp = @truncate(u16, record.key.len); std.mem.writeIntSliceLittle(u16, buf[offset .. offset + @sizeOf(u16)], temp); offset += @sizeOf(u16); // TODO Write a function that "Reads as stream" (alas Read interface) instead of copying values std.mem.copy(u8, buf[offset .. offset + record.key.len], record.key); offset += record.key.len; std.mem.copy(u8, buf[offset .. offset + record.value.len], record.value); return record.record_size_in_bytes; } pub fn toBytesAlloc(record: *Record, alloc: *std.mem.Allocator) ![]u8 { var buf = try alloc.alloc(u8, record.bytesLen()); _ = toBytes(record, buf) catch |err| return err; return buf; } pub fn fromBytes(buf: []u8, allocator: *std.mem.Allocator) ?*Record { // Check if there's enough data to read the record size if (buf.len < @sizeOf(RecordLengthType)) { return null; } var offset: usize = 0; var op = @intToEnum(Op, buf[offset]); offset += 1; //Read the record length bytes (4 or 8 usually) to get the total length of the record const bytes_for_record_length = buf[offset .. offset + @sizeOf(RecordLengthType)]; const record_length = std.mem.readIntSliceLittle(RecordLengthType, bytes_for_record_length); offset += @sizeOf(RecordLengthType); // check if the buffer actually has the amount of bytes that the record_length says if (buf.len < record_length) { return null; } // read the key length const bytes_for_key_length = buf[offset .. offset + @sizeOf(KeyLengthType)]; const key_length = std.mem.readIntSliceLittle(KeyLengthType, bytes_for_key_length); offset += @sizeOf(u16); // read the key const key = buf[offset .. offset + key_length]; offset += key_length; // read as many bytes as left to get the value const value_length = record_length - bytes_for_key_length.len - key_length - @sizeOf(RecordLengthType) - 1; const value = buf[offset .. offset + value_length]; var r = Record.init(key, value, op, allocator) catch return null; return r; } test "record.toBytesAlloc" { var alloc = std.testing.allocator; var r = try Record.init("hello", "world", Op.Delete, &alloc); defer r.deinit(); var buf = try toBytesAlloc(r, &alloc); defer alloc.free(buf); try std.testing.expectStringEndsWith(buf, "helloworld"); try expect(!std.mem.eql(u8, buf, "helloworld")); try expectEq(@as(usize, 21), r.bytesLen()); try expectEq(buf[0], @enumToInt(Op.Delete)); } test "record.toBytes returns a contiguous array with the record" { var alloc = std.testing.allocator; var r = try Record.init("hello", "world", Op.Delete, &alloc); defer r.deinit(); var buf = try alloc.alloc(u8, r.bytesLen()); defer alloc.free(buf); const total_bytes = try toBytes(r, buf); try expectEq(@as(usize, 21), total_bytes); try std.testing.expectStringEndsWith(buf, "helloworld"); try expect(!std.mem.eql(u8, buf, "helloworld")); try expectEq(@as(usize, 21), r.bytesLen()); try expectEq(buf[0], @enumToInt(Op.Delete)); } test "record.read_record having an slice, read a record starting at an offset" { // var offset = 0; var record_bytes = [_]u8{ 0, //Op 21, 0, 0, 0, 0, 0, 0, 0, //21 bytes 5, 0, //5 bytes of key 104, 101, 108, 108, 111, //hello (the key) 119, 111, 114, 108, 100, //world (the value) }; var alloc = std.testing.allocator; const r = lsmtree.serialize.record.fromBytes(record_bytes[0..], &alloc).?; defer r.deinit(); try std.testing.expectEqualStrings("hello", r.key); try std.testing.expectEqualStrings("world", r.value); // return none if there's not enough data for a record in the buffer // starting from 20, there's not enough data to read a potential record size const r2 = lsmtree.serialize.record.fromBytes(record_bytes[20..], &alloc); try expect(r2 == null); // return none in case of some corruption where I can read the record // size but there's not enough data. For example if record size says that // the record has 30 bytes but the buffer actually has 10 const r3 = lsmtree.serialize.record.fromBytes(record_bytes[0..10], &alloc); try expect(r3 == null); }
src/serialize/record.zig
usingnamespace @import("core.zig"); const panic = std.debug.panic; pub const GeneralPurposeAllocator: type = std.heap.GeneralPurposeAllocator(.{ .enable_memory_limit = true }); const glfw = @import("glfw"); const Input = @import("input.zig").Input; const renderer = @import("renderer.zig"); pub fn main() !void { // var identity = Matrix4.identity; // var scale = Matrix4.scale(Vector3.new(1, 2, 3)); // var translation = Matrix4.translation(Vector3.new(1, 2, 3)); // var rotation = Matrix4.rotation(Quaternion.axisAngle(Vector3.yaxis, 3.1415926 / 4.0)); // var multiply = translation.mul(scale).mul(rotation); // var model = Matrix4.model(Vector3.new(1, 2, 3), Quaternion.axisAngle(Vector3.yaxis, 3.1415926 / 4.0), Vector3.new(1, 2, 3)); // var perspective = Matrix4.perspective_lh_zo(3.1415926 / 4.0, 1, 0.1, 100); // std.log.info("Identity : {d:0.2}", .{identity.data}); // std.log.info("scale : {d:0.2}", .{scale.data}); // std.log.info("translation: {d:0.2}", .{translation.data}); // std.log.info("rotation : {d:0.2}", .{rotation.data}); // std.log.info("multiply : {d:0.2}", .{multiply.data}); // std.log.info("model : {d:0.2}", .{model.data}); // std.log.info("perspective: {d:0.2}", .{perspective.data}); var global_allocator: GeneralPurposeAllocator = GeneralPurposeAllocator{}; defer { const leaked = global_allocator.deinit(); if (leaked) panic("Error: memory leaked", .{}); } var allocator = &global_allocator.allocator; try glfw.init(); defer glfw.terminate(); try glfw.Window.hint(.client_api, glfw.no_api); const window = try glfw.Window.create(1600, 900, "Saturn V0.0", null, null); defer window.destroy(); try window.maximize(); var input = try Input.init(window, allocator); defer input.deinit(); var vulkan_renderer = try renderer.Renderer.init(allocator, window); defer vulkan_renderer.deinit(); var prev_time: f64 = 0.0; while (!window.shouldClose()) { var current_time = glfw.getTime(); input.update(); try glfw.pollEvents(); vulkan_renderer.update(window, &input, @floatCast(f32, current_time - prev_time)); try vulkan_renderer.render(); prev_time = current_time; } }
src/main.zig
const std = @import("std"); const root = @import("main.zig"); const math = std.math; const testing = std.testing; pub const vec2 = Vec2(f32); pub const vec2_f64 = Vec2(f64); pub const vec2_i32 = Vec2(i32); /// A 2 dimensional vector. pub fn Vec2(comptime T: type) type { if (@typeInfo(T) != .Float and @typeInfo(T) != .Int) { @compileError("Vec2 not implemented for " ++ @typeName(T)); } return packed struct { x: T, y: T, const Self = @This(); /// Constract vector from given 3 components. pub fn new(x: T, y: T) Self { return .{ .x = x, .y = y }; } /// Set all components to the same given value. pub fn set(val: T) Self { return Self.new(val, val); } pub fn zero() Self { return Self.new(0.0, 0.0); } pub fn up() Self { return Self.new(0.0, 1.0); } /// Cast a type to another type. Only for integers and floats. /// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt pub fn cast(self: Self, dest: anytype) Vec2(dest) { const source_info = @typeInfo(T); const dest_info = @typeInfo(dest); if (source_info == .Float and dest_info == .Int) { const x = @floatToInt(dest, self.x); const y = @floatToInt(dest, self.y); return Vec2(dest).new(x, y); } if (source_info == .Int and dest_info == .Float) { const x = @intToFloat(dest, self.x); const y = @intToFloat(dest, self.y); return Vec2(dest).new(x, y); } return switch (dest_info) { .Float => { const x = @floatCast(dest, self.x); const y = @floatCast(dest, self.y); return Vec2(dest).new(x, y); }, .Int => { const x = @intCast(dest, self.x); const y = @intCast(dest, self.y); return Vec2(dest).new(x, y); }, else => panic( "Error, given type should be integers or float.\n", .{}, ), }; } /// Construct new vector from slice. pub fn from_slice(slice: []const T) Self { return Self.new(slice[0], slice[1]); } /// Transform vector to array. pub fn to_array(self: Self) [2]T { return .{ self.x, self.y }; } /// Return the angle in degrees between two vectors. pub fn get_angle(left: Self, right: Self) T { const dot_product = Self.dot(left.norm(), right.norm()); return root.to_degrees(math.acos(dot_product)); } /// Compute the length (magnitude) of given vector |a|. pub fn length(self: Self) T { return math.sqrt((self.x * self.x) + (self.y * self.y)); } /// Construct new normalized vector from a given vector. pub fn norm(self: Self) Self { var l = length(self); return Self.new(self.x / l, self.y / l); } pub fn is_eq(left: Self, right: Self) bool { return left.x == right.x and left.y == right.y; } /// Substraction between two given vector. pub fn sub(left: Self, right: Self) Self { return Self.new(left.x - right.x, left.y - right.y); } /// Addition betwen two given vector. pub fn add(left: Self, right: Self) Self { return Self.new(left.x + right.x, left.y + right.y); } /// Multiply each components by the given scalar. pub fn scale(v: Self, scalar: T) Self { return Self.new(v.x * scalar, v.y * scalar); } /// Return the dot product between two given vector. pub fn dot(left: Self, right: Self) T { return (left.x * right.x) + (left.y * right.y); } /// Lerp between two vectors. pub fn lerp(left: Self, right: Self, t: T) Self { const x = root.lerp(T, left.x, right.x, t); const y = root.lerp(T, left.y, right.y, t); return Self.new(x, y); } /// Construct a new vector from the min components between two vectors. pub fn min(left: Self, right: Self) Self { return Self.new( math.min(left.x, right.x), math.min(left.y, right.y), ); } /// Construct a new vector from the max components between two vectors. pub fn max(left: Self, right: Self) Self { return Self.new( math.max(left.x, right.x), math.max(left.y, right.y), ); } }; } test "zalgebra.Vec2.init" { var _vec_0 = vec2.new(1.5, 2.6); testing.expectEqual(_vec_0.x, 1.5); testing.expectEqual(_vec_0.y, 2.6); } test "zalgebra.Vec2.set" { var _vec_0 = vec2.new(2.5, 2.5); var _vec_1 = vec2.set(2.5); testing.expectEqual(vec2.is_eq(_vec_0, _vec_1), true); } test "zalgebra.Vec2.get_angle" { var _vec_0 = vec2.new(1., 0.); var _vec_1 = vec2.up(); var _vec_2 = vec2.new(-1., 0.); var _vec_3 = vec2.new(1., 1.); testing.expectEqual(vec2.get_angle(_vec_0, _vec_1), 90.); testing.expectEqual(vec2.get_angle(_vec_0, _vec_2), 180.); testing.expectEqual(vec2.get_angle(_vec_0, _vec_3), 45.); } test "zalgebra.Vec2.to_array" { const _vec_0 = vec2.up().to_array(); const _vec_1 = [_]f32{ 0, 1 }; testing.expectEqual(std.mem.eql(f32, &_vec_0, &_vec_1), true); } test "zalgebra.Vec2.is_eq" { var _vec_0 = vec2.new(1., 2.); var _vec_1 = vec2.new(1., 2.); var _vec_2 = vec2.new(1.5, 2.); testing.expectEqual(vec2.is_eq(_vec_0, _vec_1), true); testing.expectEqual(vec2.is_eq(_vec_0, _vec_2), false); } test "zalgebra.Vec2.length" { var _vec_0 = vec2.new(1.5, 2.6); testing.expectEqual(_vec_0.length(), 3.00166606); } test "zalgebra.Vec2.normalize" { var _vec_0 = vec2.new(1.5, 2.6); testing.expectEqual(vec2.is_eq(_vec_0.norm(), vec2.new(0.499722480, 0.866185605)), true); } test "zalgebra.Vec2.sub" { var _vec_0 = vec2.new(1., 2.); var _vec_1 = vec2.new(2., 2.); testing.expectEqual(vec2.is_eq(vec2.sub(_vec_0, _vec_1), vec2.new(-1., 0.)), true); } test "zalgebra.Vec2.add" { var _vec_0 = vec2.new(1., 2.); var _vec_1 = vec2.new(2., 2.); testing.expectEqual(vec2.is_eq(vec2.add(_vec_0, _vec_1), vec2.new(3., 4.)), true); } test "zalgebra.Vec2.scale" { var _vec_0 = vec2.new(1., 2.); testing.expectEqual(vec2.is_eq(vec2.scale(_vec_0, 5.), vec2.new(5., 10.)), true); } test "zalgebra.Vec2.dot" { var _vec_0 = vec2.new(1.5, 2.6); var _vec_1 = vec2.new(2.5, 3.45); testing.expectEqual(vec2.dot(_vec_0, _vec_1), 12.7200002); } test "zalgebra.Vec2.lerp" { var _vec_0 = vec2.new(-10.0, 0.0); var _vec_1 = vec2.new(10.0, 10.0); testing.expectEqual(vec2.is_eq(vec2.lerp(_vec_0, _vec_1, 0.5), vec2.new(0.0, 5.0)), true); } test "zalgebra.Vec2.min" { var _vec_0 = vec2.new(10.0, -2.0); var _vec_1 = vec2.new(-10.0, 5.0); testing.expectEqual(vec2.is_eq(vec2.min(_vec_0, _vec_1), vec2.new(-10.0, -2.0)), true); } test "zalgebra.Vec2.max" { var _vec_0 = vec2.new(10.0, -2.0); var _vec_1 = vec2.new(-10.0, 5.0); testing.expectEqual(vec2.is_eq(vec2.max(_vec_0, _vec_1), vec2.new(10.0, 5.0)), true); } test "zalgebra.Vec2.from_slice" { const array = [2]f32{ 2, 4 }; testing.expectEqual(vec2.is_eq(vec2.from_slice(&array), vec2.new(2, 4)), true); } test "zalgebra.Vec2.cast" { const a = vec2_i32.new(3, 6); const b = Vec2(usize).new(3, 6); testing.expectEqual( Vec2(usize).is_eq(a.cast(usize), b), true, ); const c = vec2.new(3.5, 6.5); const d = vec2_f64.new(3.5, 6.5); testing.expectEqual( vec2_f64.is_eq(c.cast(f64), d), true, ); const e = vec2_i32.new(3, 6); const f = vec2.new(3.0, 6.0); testing.expectEqual( vec2.is_eq(e.cast(f32), f), true, ); const g = vec2.new(3.0, 6.0); const h = vec2_i32.new(3, 6); testing.expectEqual( vec2_i32.is_eq(g.cast(i32), h), true, ); }
src/vec2.zig
const std = @import("std"); const assert = std.debug.assert; const Computer = @import("./computer.zig").Computer; pub const Bank = struct { node: [5]Computer, pub fn init(str: []const u8) Bank { var self = Bank{ .node = undefined, }; var j: usize = 0; while (j < self.node.len) : (j += 1) { self.node[j] = Computer.init(str); self.node[j].setReentrant(); } return self; } pub fn deinit(self: *Bank) void { var j: usize = 0; while (j < self.node.len) : (j += 1) { self.node[j].deinit(); } } pub fn setReentrant(self: *Bank) void { var j: usize = 0; while (j < self.node.len) : (j += 1) { self.node[j].setReentrant(); } } pub fn clear(self: *Bank) void { var j: usize = 0; while (j < self.node.len) : (j += 1) { self.node[j].clear(); } } pub fn get_thruster_signal(self: *Bank, phases: [5]u8) i32 { self.clear(); const top = self.node.len; var n: usize = 0; while (n < top) : (n += 1) { self.node[n].enqueueInput(phases[n]); } n = 0; var previous: ?i32 = 0; var result: i32 = 0; while (true) { if (self.node[n].halted) { // std.debug.warn("NODE {} halted\n", n); if (n == top - 1) break; } else if (previous != null) { self.node[n].enqueueInput(previous.?); const output = self.node[n].run(); if (output != null and n == top - 1) { result = output.?; } previous = output; } else { std.debug.warn("NODE {} is paused but there is no input\n", .{n}); break; } n = (n + 1) % phases.len; } return result; } pub fn optimize_thruster_signal(self: *Bank, phases: *[5]u8) i32 { var mt: i32 = std.math.minInt(i32); self.ots(phases, phases.*.len, &mt); return mt; } fn ots(self: *Bank, phases: *[5]u8, len: usize, mt: *i32) void { if (len == 1) { const t = self.get_thruster_signal(phases.*); if (mt.* < t) { mt.* = t; } return; } var j: usize = 0; while (j < phases.len) : (j += 1) { const m = len - 1; std.mem.swap(u8, &phases[j], &phases[m]); self.ots(phases, m, mt); std.mem.swap(u8, &phases[j], &phases[m]); } } }; test "thruster signals, non-reentrant, short program" { const code: []const u8 = "3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0"; const phases = [5]u8{ 4, 3, 2, 1, 0 }; var bank = Bank.init(code[0..]); assert(bank.get_thruster_signal(phases) == 43210); } test "thruster signals, non-reentrant, medium program" { const code: []const u8 = "3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0"; const phases = [5]u8{ 0, 1, 2, 3, 4 }; var bank = Bank.init(code[0..]); assert(bank.get_thruster_signal(phases) == 54321); } test "thruster signals, non-reentrant, long program" { const code: []const u8 = "3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0"; const phases = [5]u8{ 1, 0, 4, 3, 2 }; var bank = Bank.init(code[0..]); assert(bank.get_thruster_signal(phases) == 65210); } test "optimize thruster signals, non-reentrant, short program" { const code: []const u8 = "3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0"; var bank = Bank.init(code[0..]); var phases = [5]u8{ 0, 1, 2, 3, 4 }; // must be sorted assert(bank.optimize_thruster_signal(&phases) == 43210); } test "thruster signals, reentrant, short program" { const code: []const u8 = "3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5"; const phases = [5]u8{ 9, 8, 7, 6, 5 }; var bank = Bank.init(code[0..]); assert(bank.get_thruster_signal(phases) == 139629729); } test "thruster signals, reentrant, medium program" { const code: []const u8 = "3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10"; const phases = [5]u8{ 9, 7, 8, 5, 6 }; var bank = Bank.init(code[0..]); assert(bank.get_thruster_signal(phases) == 18216); }
2019/p07/bank.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec2 = tools.Vec2; const Map = tools.Map(u8, 32, 32, false); const Unit = struct { const Type = enum { goblin, elf }; type: Type, hit_points: u16 = 200, attack: u16 = 3, p: Vec2, fn lessThan(_: void, lhs: Unit, rhs: Unit) bool { return Vec2.lessThan({}, lhs.p, rhs.p); } }; fn compute_dists(cavern: *const Map, units: []const Unit, o: Vec2) Map { var m = Map{ .default_tile = 255 }; m.bbox = cavern.bbox; m.fill(255, null); var dirty = true; while (dirty) { dirty = false; var it = m.iter(null); while (it.nextPos()) |p| { const cav = cavern.at(p); if (cav == '#') continue; if (Vec2.eq(p, o)) { if (m.at(p) != 0) { m.set(p, 0); dirty = true; } continue; } const blocked = for (units) |u| { if (u.hit_points == 0) continue; if (u.p.eq(p)) break true; } else false; if (blocked) continue; const left = m.at(Vec2{ .x = p.x - 1, .y = p.y }); const right = m.at(Vec2{ .x = p.x + 1, .y = p.y }); const up = m.at(Vec2{ .x = p.x, .y = p.y - 1 }); const down = m.at(Vec2{ .x = p.x, .y = p.y + 1 }); const old = m.at(p); const new = std.math.min(std.math.min(left, right), std.math.min(up, down)); if (new == 255) continue; if (old != new + 1) { m.set(p, new + 1); dirty = true; } } } return m; } fn debug_print_state(cavern: *const Map, units: []const Unit) void { var m = cavern.*; for (units) |u| { if (u.hit_points == 0) continue; assert(m.at(u.p) == '.'); m.set(u.p, if (u.type == .elf) 'E' else 'G'); } var buf: [5000]u8 = undefined; std.debug.print("{}\n", .{m.printToBuf(null, null, null, &buf)}); } fn playout(cavern: *const Map, units: []Unit) u32 { var round: u32 = 0; while (true) { std.sort.sort(Unit, units, {}, Unit.lessThan); for (units) |*it| { if (it.hit_points == 0) continue; // std.debug.print("examining unit @{}...\n", .{it.p}); const dists = compute_dists(cavern, units, it.p); const enemy_type: Unit.Type = if (it.type == .elf) .goblin else .elf; var candidates: [16]Vec2 = undefined; var best_dist: u32 = 255; var best_nb: u32 = 0; var no_enemies = true; for (units) |other| { if (other.hit_points == 0) continue; if (other.type != enemy_type) continue; // std.debug.print("...examining adjacent to @{}\n", .{other.p}); no_enemies = false; const p = other.p; for (Vec2.cardinal_dirs) |d| { const p0 = Vec2{ .x = p.x + d.x, .y = p.y + d.y }; const dist = dists.at(p0); // std.debug.print("..... d={} {}\n", .{ dist, p0 }); if (dist == 255) continue; if (dist < best_dist) { best_dist = dist; best_nb = 1; candidates[0] = p0; } else if (dist == best_dist) { candidates[best_nb] = p0; best_nb += 1; } } } if (best_nb == 0) { continue; // can't move } std.sort.sort(Vec2, candidates[0..best_nb], {}, Vec2.lessThan); // std.debug.print("...moving to @{}\n", .{candidates[0]}); const back_dists = compute_dists(cavern, units, candidates[0]); var best_back_dist = back_dists.at(it.p); var best_pos = it.p; for (Vec2.cardinal_dirs) |d| { const p0 = it.p.add(d); const back_dist = back_dists.at(p0); if (best_back_dist > back_dist) { best_back_dist = back_dist; best_pos = p0; } } it.p = best_pos; // move! // std.debug.print("...via {}\n", .{best_pos}); // attack? var best_target: ?*Unit = null; var best_hitpoints: u16 = 255; for (Vec2.cardinal_dirs) |d| { const p0 = it.p.add(d); for (units) |*other| { if (other.hit_points == 0) continue; if (other.type != enemy_type) continue; if (!other.p.eq(p0)) continue; if (other.hit_points < best_hitpoints) { best_hitpoints = other.hit_points; best_target = other; } } } if (best_target) |t| { t.hit_points = if (t.hit_points > it.attack) t.hit_points - it.attack else 0; } } var alive = [2]bool{ false, false }; for (units) |it| { if (it.hit_points != 0) alive[@enumToInt(it.type)] = true; } if (!alive[0] or !alive[1]) { return round; } round += 1; // debug_print_state(params.cavern, units); } } pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { const params: struct { cavern: *const Map, units: []const Unit } = blk: { const cavern = try allocator.create(Map); errdefer allocator.destroy(cavern); cavern.bbox = tools.BBox.empty; cavern.default_tile = 0; const units = try allocator.alloc(Unit, 100); errdefer allocator.free(units); var nb_units: usize = 0; var y: i32 = 0; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { for (line) |sq, i| { const p = Vec2{ .x = @intCast(i32, i), .y = y }; switch (sq) { '#' => cavern.set(p, '#'), '.' => cavern.set(p, '.'), 'G' => { cavern.set(p, '.'); units[nb_units] = Unit{ .p = p, .type = .goblin }; nb_units += 1; }, 'E' => { cavern.set(p, '.'); units[nb_units] = Unit{ .p = p, .type = .elf }; nb_units += 1; }, else => { std.debug.print("unknown unit '{c}'\n", .{sq}); return error.UnsupportedInput; }, } } y += 1; } break :blk .{ .cavern = cavern, .units = units[0..nb_units] }; }; defer allocator.destroy(params.cavern); defer allocator.free(params.units); //var buf: [5000]u8 = undefined; //std.debug.print("{}\n", .{params.cavern.printToBuf(null, null, null, &buf)}); // part1 const ans1 = ans: { const units = try allocator.dupe(Unit, params.units); defer allocator.free(units); const round = playout(params.cavern, units); //debug_print_state(params.cavern, units); var total: u32 = 0; for (units) |it| { if (it.hit_points == 0) continue; // std.debug.print(" unit hp: {}\n", .{it.hit_points}); total += it.hit_points; } //std.debug.print("Total {}x{}\n", .{ round, total }); break :ans total * round; }; // part2 const ans2 = ans: { var attack: u16 = 30; // 4 while (true) : (attack += 1) { const units = try allocator.dupe(Unit, params.units); defer allocator.free(units); var nb_elves: u32 = 0; for (units) |*u| { if (u.type == .elf) { u.attack = attack; nb_elves += 1; } } const round = playout(params.cavern, units); //debug_print_state(params.cavern, units); var total: u32 = 0; var alive_elves: u32 = 0; for (units) |it| { if (it.hit_points == 0) continue; if (it.type == .elf) { alive_elves += 1; } //std.debug.print(" unit hp: {}\n", .{it.hit_points}); total += it.hit_points; } //std.debug.print("Total {}x{}\n", .{ round, total }); if (alive_elves == nb_elves) break :ans total * round; } }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day15.txt", run);
2018/day15.zig
const sf = @import("../sfml.zig"); pub const View = struct { const Self = @This(); /// Creates a view from a rectangle pub fn fromRect(rect: sf.FloatRect) Self { var ret: Self = undefined; ret.center = rect.getCorner(); ret.size = rect.getSize(); ret.center = ret.center.add(ret.size.scale(0.5)); ret.viewport = sf.FloatRect.init(0, 0, 1, 1); return ret; } /// Creates a view from a CSFML object /// This is mainly for the inner workings of this wrapper pub fn fromCSFML(view: *const sf.c.sfView) Self { var ret: Self = undefined; ret.center = sf.Vector2f.fromCSFML(sf.c.sfView_getCenter(view)); ret.size = sf.Vector2f.fromCSFML(sf.c.sfView_getSize(view)); ret.viewport = sf.FloatRect.fromCSFML(sf.c.sfView_getViewport(view)); return ret; } /// Creates a CSFML view from this view /// This is mainly for the inner workings of this wrapper /// The resulting view must be destroyed! pub fn toCSFML(self: Self) *sf.c.sfView { var view = sf.c.sfView_create().?; sf.c.sfView_setCenter(view, self.center.toCSFML()); sf.c.sfView_setSize(view, self.size.toCSFML()); sf.c.sfView_setViewport(view, self.viewport.toCSFML()); return view; } pub fn getRect(self: Self) sf.FloatRect { return sf.FloatRect.init( self.center.x - self.size.x / 2, self.center.y - self.size.y / 2, self.size.x, self.size.y ); } // View variables /// Center of the view, what this view "looks" at center: sf.Vector2f, /// Width and height of the view size: sf.Vector2f, /// The viewport of this view viewport: sf.FloatRect }; test "view: from rect" { const tst = @import("std").testing; // Testing if the view from rect initialization works var rect = sf.FloatRect.init(10, -15, 700, 600); var view = sf.c.sfView_createFromRect(rect.toCSFML()); defer sf.c.sfView_destroy(view); var view2 = View.fromRect(rect); var center = sf.Vector2f.fromCSFML(sf.c.sfView_getCenter(view)); var size = sf.Vector2f.fromCSFML(sf.c.sfView_getSize(view)); tst.expectWithinMargin(center.x, view2.center.x, 0.00001); tst.expectWithinMargin(center.y, view2.center.y, 0.00001); tst.expectWithinMargin(size.x, view2.size.x, 0.00001); tst.expectWithinMargin(size.y, view2.size.y, 0.00001); var rect_ret = view2.getRect(); tst.expectWithinMargin(rect.left, rect_ret.left, 0.00001); tst.expectWithinMargin(rect.top, rect_ret.top, 0.00001); tst.expectWithinMargin(rect.width, rect_ret.width, 0.00001); tst.expectWithinMargin(rect.height, rect_ret.height, 0.00001); }
src/sfml/graphics/view.zig
const std = @import("std"); const Buffer = std.Buffer; const warn = std.debug.warn; const assert = std.debug.assert; const mem = std.mem; const Allocator = mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const encoding = enum { path, pathSegment, host, zone, userPassword, queryComponent, fragment, }; pub const Error = error{ EscapeError, InvalidHostError, }; fn shouldEscape(c: u8, mode: encoding) bool { if ('A' <= c and c <= 'Z' or 'a' <= c and c <= 'z' or '0' <= c and c <= '9') { return false; } if (mode == encoding.host or mode == encoding.zone) { switch (c) { '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"' => return false, else => {}, } } switch (c) { '-', '_', '.', '~' => return false, '$', '&', '+', ',', '/', ':', ';', '=', '?', '@' => { switch (mode) { encoding.path => return c == '?', encoding.pathSegment => return c == '/' or c == ';' or c == ',' or c == '?', encoding.userPassword => return c == '@' or c == '/' or c == '?' or c == ':', encoding.queryComponent => return true, encoding.fragment => return false, else => {}, } }, else => {}, } if (mode == encoding.fragment) { switch (c) { '!', '(', ')', '*' => return false, else => {}, } } return true; } fn ishex(c: u8) bool { if ('0' <= c and c <= '9') { return true; } if ('a' <= c and c <= 'f') { return true; } if ('A' <= c and c <= 'F') { return true; } return false; } fn unhex(c: u8) u8 { if ('0' <= c and c <= '9') { return c - '0'; } if ('a' <= c and c <= 'f') { return c - 'a' + 10; } if ('A' <= c and c <= 'F') { return c - 'A' + 10; } return 0; } fn is25(s: []const u8) bool { return mem.eql(u8, s, "%25"); } fn unescape(t: []u8, ctx: UnescapeContext, s: []const u8, mode: encoding) void { if (ctx.canUnEscape()) { var j: usize = 0; var i: usize = 0; while (i < s.len) { switch (s[i]) { '%' => { t[j] = unhex(s[i + 1]) << 4 | unhex(s[i + 2]); j = j + 1; i = i + 3; }, '+' => { if (mode == encoding.queryComponent) { t[j] = ' '; } else { t[j] = '+'; } j = j + 1; i = i + 1; }, else => { t[j] = s[i]; j = j + 1; i = i + 1; }, } } } else { mem.copy(u8, t, s); } } const UnescapeContext = struct { buffer_size: usize, has_plus: bool, length: usize, // returns true if we can unescape the string with the current unescape context. fn canUnEscape(self: UnescapeContext) bool { return !(self.buffer_size == self.length and !self.has_plus); } fn len(self: UnescapeContext) usize { return self.buffer_size; } }; // countEscape calcutates and reurns the size of the buffer necessary for // storing unescaped s. fn countUneEscape(s: []const u8, mode: encoding) !UnescapeContext { var n: usize = 0; var has_plus: bool = true; var i: usize = 0; while (i < s.len) { switch (s[i]) { '%' => { n = n + 1; if (i + 2 >= s.len or !ishex(s[i + 1]) or !ishex(s[i + 2])) { return Error.EscapeError; } if (mode == encoding.host and unhex(s[i + 1]) < 9 and !is25(s[i .. i + 3])) { return Error.EscapeError; } if (mode == encoding.zone) { const v = unhex(s[i + 1]) << 4 | unhex(s[i + 2]); if (!is25(s[i .. i + 3]) and v != ' ' and shouldEscape(v, encoding.host)) { return Error.EscapeError; } } i = i + 3; }, '+' => { has_plus = mode == encoding.queryComponent; i = i + 1; }, else => { if ((mode == encoding.host or mode == encoding.zone) and s[i] < 0x80 and shouldEscape(s[i], mode)) { return Error.InvalidHostError; } i = i + 1; }, } } return UnescapeContext{ .buffer_size = s.len - 2 * n, .has_plus = has_plus, .length = s.len, }; } pub fn queryUnescape(a: *std.Buffer, s: []const u8) !void { const ctx = try countUneEscape(s, encoding.queryComponent); try a.resize(ctx.buffer_size); unescape(a.toSlice(), ctx, s, encoding.queryComponent); } pub fn pathUnescape(a: *std.Buffer, s: []const u8) !void { const ctx = try countUneEscape(s, encoding.pathSegment); try a.resize(ctx.buffer_size); unescape(a.toSlice(), ctx, s, encoding.pathSegment); } pub fn pathEscape(a: *std.Buffer, s: []const u8) !void { const ctx = countEscape(s, encoding.pathSegment); try a.resize(ctx.len()); escape(a.toSlice(), ctx, s, encoding.pathSegment); } pub fn queryEscape(a: *std.Buffer, s: []const u8) !void { const ctx = countEscape(s, encoding.queryComponent); try a.resize(ctx.len()); return escape(a.toSlice(), ctx, s, encoding.queryComponent); } const EscapeContext = struct { space_count: usize, hex_count: usize, length: usize, fn canEscape(self: EscapeContext) bool { return !(self.space_count == 0 and self.hex_count == 0); } fn len(self: EscapeContext) usize { return self.length + 2 * self.hex_count; } }; fn escape(t: []u8, ctx: EscapeContext, s: []const u8, mode: encoding) void { if (ctx.canEscape()) { var i: usize = 0; if (ctx.hex_count == 0) { while (i < s.len) { if (s[i] == ' ') { t[i] = '+'; } else { t[i] = s[i]; } i = i + 1; } } else { i = 0; var j: usize = 0; const alpha: []const u8 = "0123456789ABCDEF"; while (i < s.len) { const c = s[i]; if (c == ' ' and mode == encoding.queryComponent) { t[j] = '+'; j = j + 1; } else if (shouldEscape(c, mode)) { t[j] = '%'; t[j + 1] = alpha[c >> 4]; t[j + 2] = alpha[c & 15]; j = j + 3; } else { t[j] = s[i]; j = j + 1; } i = i + 1; } } } else { mem.copy(u8, t, s); } } fn shouldEscapeString(s: []const u8) bool { return countEscape(s).canEscape(); } fn shouldUnEscapeString(s: []const u8) !bool { const ctx = try countUneEscape(s); return ctx.canUnEscape(); } fn countEscape(s: []const u8, mode: encoding) EscapeContext { var spaceCount: usize = 0; var hexCount: usize = 0; for (s) |c| { if (shouldEscape(c, mode)) { if (c == ' ' and mode == encoding.queryComponent) { spaceCount = spaceCount + 1; } else { hexCount = hexCount + 1; } } } return EscapeContext{ .space_count = spaceCount, .hex_count = hexCount, .length = s.len, }; } // A URL represents a parsed URL (technically, a URI reference). // // The general form represented is: // //[scheme:][//[userinfo@]host][/]path[?query][#fragment] // // URLs that do not start with a slash after the scheme are interpreted as: // //scheme:opaque[?query][#fragment] // // Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. // A consequence is that it is impossible to tell which slashes in the Path were // slashes in the raw URL and which were %2f. This distinction is rarely important, // but when it is, code must not use Path directly. // The Parse function sets both Path and RawPath in the URL it returns, // and URL's String method uses RawPath if it is a valid encoding of Path, // by calling the EscapedPath method. pub const URL = struct { scheme: ?[]const u8, opaque: ?[]const u8, user: ?UserInfo, host: ?[]const u8, path: ?[]const u8, raw_path: ?[]const u8, force_query: bool, raw_query: ?[]const u8, fragment: ?[]const u8, arena: ArenaAllocator, const Scheme = struct { scheme: ?[]const u8, path: []const u8, }; fn init(a: *Allocator) URL { var u: URL = undefined; u.arena = ArenaAllocator.init(a); return u; } fn deinit(self: *URL) void { self.arena.deinit(); } pub fn getScheme(raw: []const u8) !Scheme { var i: usize = 0; var u: Scheme = undefined; while (i < raw.len) { const c = raw[i]; if ('a' <= c and c <= 'z' or 'A' <= c and c <= 'Z') { // do nothing } else if ('0' <= c and c <= '9' and c == '+' and c == '-' and c == '.') { if (i == 0) { u.path = raw; return u; } } else if (c == ':') { if (i == 0) { return error.MissingProtocolScheme; } u.scheme = raw[0..i]; u.path = raw[i + 1 ..]; return u; } else { // we have encountered an invalid character, // so there is no valid scheme u.path = raw; return u; } i = i + 1; } u.path = raw; return u; } const SplitResult = struct { x: []const u8, y: ?[]const u8, }; fn split(s: []const u8, c: []const u8, cutc: bool) SplitResult { if (mem.indexOf(u8, s, c)) |i| { if (cutc) { return SplitResult{ .x = s[0..i], .y = s[i + c.len ..], }; } return SplitResult{ .x = s[0..i], .y = s[i..], }; } return SplitResult{ .x = s, .y = null }; } pub fn parse(a: *Allocator, raw_url: []const u8) !URL { var uri = init(a); var u = &uri; // we allocate once and copy all the url. This will allow us to be sure // that the strings are available throughout the lifetime of the URL // instance until URL.deinit is called. // var al = &u.arena.allocator; // var copy_raw = try al.alloc(u8, raw_url.len); // mem.copy(u8, copy_raw, raw_url); errdefer u.deinit(); const frag = split(raw_url, "#", true); try parseInternal(u, frag.x, false); if (frag.y == null) { return uri; } const ctx = try countUneEscape(frag.y.?, encoding.path); var al = &u.arena.allocator; var f = try al.alloc(u8, ctx.buffer_size); unescape(f, ctx, frag.y.?, encoding.path); u.fragment = f; return uri; } pub fn encode(u: *URL, buf: *Buffer) !void { try buf.resize(0); if (u.scheme) |scheme| { try buf.append(scheme); try buf.appendByte(':'); } if (u.opaque) |opaque| { try buf.append(opaque); } else { if (u.scheme != null or u.host != null or u.user != null) { if (u.host != null or u.path != null or u.user != null) { try buf.append("//"); } if (u.user != null) { try u.user.?.encode(buf); try buf.appendByte('@'); } if (u.host) |h| { const x = buf.len(); const ctx = countEscape(h, encoding.host); try buf.resize(x + ctx.len()); escape(buf.toSlice()[x..], ctx, h, encoding.host); } } var pathBuf = &try Buffer.init(buf.list.allocator, ""); defer pathBuf.deinit(); try escapedPath(u, pathBuf); const p = pathBuf.toSlice(); if (p.len > 0 and p[0] != '/' and u.host != null) { try buf.appendByte('/'); } if (buf.len() == 0) { // RFC 3986 §4.2 // A path segment that contains a colon character (e.g., "this:that") // cannot be used as the first segment of a relative-path reference, as // it would be mistaken for a scheme name. Such a segment must be // preceded by a dot-segment (e.g., "./this:that") to make a relative- // path reference. if (mem.indexOfScalar(u8, p, ':')) |idx| { const nx = mem.indexOfScalar(u8, p[0..idx], '/'); if (nx == null) { try buf.append("./"); } } } if (p.len > 0) { try buf.append(p); } } if (u.force_query or u.raw_query != null) { try buf.appendByte('?'); if (u.raw_query) |rq| { try buf.append(rq); } } if (u.fragment) |f| { try buf.appendByte('#'); const ctx = countEscape(f, encoding.fragment); const current = buf.len(); try buf.resize(current + ctx.len()); escape(buf.toSlice()[current..], ctx, f, encoding.fragment); } } fn parseInternal(u: *URL, raw_url: []const u8, via_request: bool) !void { if (raw_url.len == 0 and via_request) { return error.EmptyURL; } if (mem.eql(u8, raw_url, "*")) { u.path = "*"; return; } const scheme = try getScheme(raw_url); var rest: []const u8 = undefined; if (scheme.scheme) |s| { // TODO: lowercase scheme // I'm afraid to pull unicode package dependency here for now, but // shcme must be lowercased. u.scheme = s; } rest = scheme.path; if (hasSuffix(rest, "?") and count(rest, "?") == 1) { u.force_query = true; rest = rest[0 .. rest.len - 1]; } else { const s = split(rest, "?", true); rest = s.x; u.raw_query = s.y; } if (!hasPrefix(rest, "/")) { if (u.scheme != null) { u.opaque = rest; return; } if (via_request) { return error.InvalidURL; } // Avoid confusion with malformed schemes, like cache_object:foo/bar. // See golang.org/issue/16822. // // RFC 3986, §3.3: // In addition, a URI reference (Section 4.1) may be a relative-path reference, // in which case the first path segment cannot contain a colon (":") character. const colon = mem.indexOf(u8, rest, ":"); const slash = mem.indexOf(u8, rest, "/"); if (colon != null and colon.? >= 0 and (slash == null or colon.? < slash.?)) { return error.BadURL; } } if ((u.scheme != null or !via_request and !hasPrefix(rest, "///")) and hasPrefix(rest, "//")) { const x = split(rest[2..], "/", false); if (x.y) |y| { rest = y; } else { rest = ""; } const au = try parseAuthority(&u.arena.allocator, x.x); u.user = au.user; u.host = au.host; } if (rest.len > 0) { try setPath(&u.arena.allocator, u, rest); } return; } const Authority = struct { user: ?UserInfo, host: []const u8, }; const hostList = struct { host_1: []const u8, host_2: []const u8, host_3: []const u8, }; fn parseAuthority(allocator: *Allocator, authority: []const u8) !Authority { const idx = lastIndex(authority, "@"); var res: Authority = undefined; if (idx == null) { res.host = try parseHost(allocator, authority); } else { res.host = try parseHost(allocator, authority[idx.? + 1 ..]); } if (idx == null) { res.user = null; return res; } const user_info = authority[0..idx.?]; if (!validUserinfo(user_info)) { return error.InvalidUserInfo; } const s = split(user_info, ":", true); var ctx = try countUneEscape(s.x, encoding.userPassword); var username = try allocator.alloc(u8, ctx.buffer_size); unescape(username, ctx, s.x, encoding.userPassword); if (s.y) |y| { ctx = try countUneEscape(y, encoding.userPassword); var password = try allocator.alloc(u8, ctx.buffer_size); unescape(password, ctx, y, encoding.userPassword); res.user = UserInfo.initWithPassword(username, password); } else { res.user = UserInfo.init(username); } return res; } fn parseHost(a: *Allocator, host: []const u8) ![]const u8 { if (hasPrefix(host, "[")) { // Parse an IP-Literal in RFC 3986 and RFC 6874. // E.g., "[fe80::1]", "[fe80::1%25en0]", "[fefc00:e968:6179::de52:7100]:80". const idx = lastIndex(host, "]"); if (idx == null) { // TODO: use result to improve error message return error.BadURL; } const i = idx.?; const colon_port = host[i + 1 ..]; if (!validOptionalPort(colon_port)) { return error.BadURL; } // RFC 6874 defines that %25 (%-encoded percent) introduces // the zone identifier, and the zone identifier can use basically // any %-encoding it likes. That's different from the host, which // can only %-encode non-ASCII bytes. // We do impose some restrictions on the zone, to avoid stupidity // like newlines. if (index(host[0..i], "%25")) |zone| { const ctx_1 = try countUneEscape(host[0..zone], encoding.host); const ctx_2 = try countUneEscape(host[zone..i], encoding.zone); const ctx_3 = try countUneEscape(host[i..], encoding.host); const required = ctx_1.buffer_size + ctx_2.buffer_size + ctx_3.buffer_size; var out_buf = try a.alloc(u8, required); unescape(out_buf[0..ctx_1.buffer_size], ctx_1, host[0..zone], encoding.host); unescape(out_buf[ctx_1.buffer_size .. ctx_1.buffer_size + ctx_2.buffer_size], ctx_2, host[zone..i], encoding.zone); unescape(out_buf[ctx_1.buffer_size + ctx_2.buffer_size .. ctx_1.buffer_size + ctx_2.buffer_size + ctx_3.buffer_size], ctx_3, host[i..], encoding.host); return out_buf; } } const ctx = try countUneEscape(host, encoding.host); var out = try a.alloc(u8, ctx.buffer_size); unescape(out, ctx, host, encoding.host); return out; } fn validOptionalPort(port: []const u8) bool { if (port.len == 0) { return true; } if (port[0] != ':') { return false; } for (port[1..]) |value| { if (value < '0' or value > '9') { return false; } } return true; } // validUserinfo reports whether s is a valid userinfo string per RFC 3986 // Section 3.2.1: // userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" // / "*" / "+" / "," / ";" / "=" // // It doesn't validate pct-encoded. The caller does that via func unescape. fn validUserinfo(s: []const u8) bool { for (s) |r| { if ('A' <= r and r <= 'Z') { continue; } if ('a' <= r and r <= 'z') { continue; } if ('0' <= r and r <= '9') { continue; } switch (r) { '-', '.', '_', ':', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', '%', '@' => {}, else => { return false; }, } } return true; } // escapedPath writes ton buf the escaped form of u.Path. // In general there are multiple possible escaped forms of any path. // EscapedPath returns u.RawPath when it is a valid escaping of u.Path. // Otherwise EscapedPath ignores u.RawPath and computes an escaped // form on its own. // The String and RequestURI methods use EscapedPath to construct // their results. // In general, code should call EscapedPath instead of // reading u.RawPath directly. fn escapedPath(u: *URL, buf: *Buffer) !void { if (u.raw_path) |raw| { if (validEncodedPath(raw)) { if (countUneEscape(raw, encoding.path)) |ctx| { try buf.resize(ctx.len()); unescape(buf.toSlice(), ctx, raw, encoding.path); if (u.path) |p| { if (buf.eql(p)) { try buf.resize(0); try buf.append(raw); return; } } } else |_| {} } } if (u.path) |p| { if (mem.eql(u8, p, "*")) { return buf.append("*"); } const ctx = countEscape(p, encoding.path); try buf.resize(ctx.len()); escape(buf.toSlice(), ctx, p, encoding.path); } } // validEncodedPath reports whether s is a valid encoded path. // It must not contain any bytes that require escaping during path encoding. fn validEncodedPath(s: []const u8) bool { for (s) |c| { // RFC 3986, Appendix A. // pchar = unreserved / pct-encoded / sub-delims / ":" / "@". // shouldEscape is not quite compliant with the RFC, // so we check the sub-delims ourselves and let // shouldEscape handle the others. switch (c) { '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@' => {}, '[', ']' => { // ok - not specified in RFC 3986 but left alone by modern browsers }, '%' => { // ok - percent encoded, will decode }, else => { if (shouldEscape(c, encoding.path)) { return false; } }, } } return true; } }; fn setPath(a: *Allocator, u: *URL, path: []const u8) !void { const uctx = try countUneEscape(path, encoding.path); var raw_path = try a.alloc(u8, uctx.buffer_size); unescape(raw_path, uctx, path, encoding.path); u.path = raw_path; const ectx = countEscape(path, encoding.path); var escaped_path = try a.alloc(u8, ectx.len()); escape(escaped_path, ectx, u.path.?, encoding.path); if (!mem.eql(u8, raw_path, escaped_path)) { var e = try a.alloc(u8, path.len); mem.copy(u8, e, path); u.raw_path = e; } } /// hasPrefix returns true if slice s begins with prefix. pub fn hasPrefix(s: []const u8, prefix: []const u8) bool { return s.len >= prefix.len and mem.eql(u8, s[0..prefix.len], prefix); } pub fn hasSuffix(s: []const u8, suffix: []const u8) bool { return s.len >= suffix.len and mem.eql(u8, s[s.len - suffix.len ..], suffix); } // naive count pub fn count(s: []const u8, sub: []const u8) usize { var x: usize = 0; var idx: usize = 0; while (idx < s.len) { if (mem.indexOf(u8, s[idx..], sub)) |i| { x += 1; idx += i + sub.len; } else { return x; } } return x; } fn lastIndex(s: []const u8, sub: []const u8) ?usize { return mem.lastIndexOf(u8, s, sub); } fn index(s: []const u8, sub: []const u8) ?usize { return mem.indexOf(u8, s, sub); } pub const UserInfo = struct { username: ?[]const u8, password: ?[]const u8, pub fn init(name: []const u8) UserInfo { return UserInfo{ .username = name, .password = <PASSWORD>, }; } pub fn initWithPassword(name: []const u8, password: []const u8) UserInfo { return UserInfo{ .username = name, .password = password, }; } pub fn encode(u: *UserInfo, buf: *std.Buffer) !void { if (u.username) |usr| { const ctx = countEscape(usr, encoding.userPassword); const x = buf.len(); try buf.resize(x + ctx.len()); escape(buf.toSlice()[x..], ctx, usr, encoding.userPassword); } if (u.password) |pass| { try buf.appendByte(':'); const ctx = countEscape(pass, encoding.userPassword); const x = buf.len(); try buf.resize(x + ctx.len()); escape(buf.toSlice()[x..], ctx, pass, encoding.userPassword); } } }; // result returns a wrapper struct that helps improve error handling. Panicking // in production is bad, and adding more context to errors improves the // experience especially with parsing. fn result(comptime Value: type, ResultError: type) type { return struct { const Self = @This(); value: Result, message: ?[]const u8, pub const Error = ResultError; pub fn withErr(e: Error, msg: ?[]const u8) Self { return Self{ .value = Result{ .err = e }, .message = msg, }; } pub fn withValue(e: Error) Self { return Self{ .value = Result{ .value = e }, .message = null, }; } pub const Result = union(enum) { err: Error, value: Value, }; pub fn unwrap(self: Self) Error!Value { return switch (self.value) { Error => |err| err, Value => |v| v, else => unreachable, }; } }; }
src/net/url/url.zig
const std = @import("std"); test "example" { const input = @embedFile("5_example.txt"); const result = try run(input); try std.testing.expectEqual(@as(u32, 5), result); } pub fn main() !void { const input = @embedFile("5.txt"); const result = try run(input); std.debug.print("{}\n", .{result}); } const Line = struct { from_x: u16, from_y: u16, to_x: u16, to_y: u16, fn parse(line: []const u8) !Line { var nums = std.mem.tokenize(u8, line, " ,->"); var fx = nums.next() orelse return error.ReadError; var fy = nums.next() orelse return error.ReadError; var tx = nums.next() orelse return error.ReadError; var ty = nums.next() orelse return error.ReadError; return Line{ .from_x = try std.fmt.parseInt(u16, fx, 10), .from_y = try std.fmt.parseInt(u16, fy, 10), .to_x = try std.fmt.parseInt(u16, tx, 10), .to_y = try std.fmt.parseInt(u16, ty, 10), }; } fn isHorizontal(self: Line) bool { return self.from_y == self.to_y; } fn isVertical(self: Line) bool { return self.from_x == self.to_x; } }; fn run(input: []const u8) !u32 { var grid: [1000][1000]u2 = .{.{0} ** 1000} ** 1000; var lines = std.mem.split(u8, input, "\n"); while (lines.next()) |l| { const line = try Line.parse(l); if (line.isHorizontal()) { const from_x = @minimum(line.from_x, line.to_x); const to_x = @maximum(line.from_x, line.to_x); const y = line.from_y; var x = from_x; while (x <= to_x) : (x += 1) { grid[x][y] +|= 1; } } if (line.isVertical()) { const x = line.from_x; const from_y = @minimum(line.from_y, line.to_y); const to_y = @maximum(line.from_y, line.to_y); var y = from_y; while (y <= to_y) : (y += 1) { grid[x][y] +|= 1; } } } var count: u32 = 0; for (grid) |row| { for (row) |n| { if (n >= 2) count += 1; } } return count; }
shritesh+zig/5a.zig
const std = @import("std"); const stdx = @import("stdx"); const fatal = stdx.fatal; const t = stdx.testing; const ds = stdx.ds; const Closure = stdx.Closure; const ClosureIface = stdx.ClosureIface; const Function = stdx.Function; const Duration = stdx.time.Duration; const string = stdx.string; const graphics = @import("graphics"); const Graphics = graphics.Graphics; const FontGroupId = graphics.FontGroupId; const FontId = graphics.FontId; const platform = @import("platform"); const EventDispatcher = platform.EventDispatcher; const ui = @import("ui.zig"); const Config = ui.Config; const Import = ui.Import; const Node = ui.Node; const Frame = ui.Frame; const BindNode = @import("frame.zig").BindNode; const FrameListPtr = ui.FrameListPtr; const FramePropsPtr = ui.FramePropsPtr; const FrameId = ui.FrameId; const ui_render = @import("render.zig"); const WidgetTypeId = ui.WidgetTypeId; const WidgetKey = ui.WidgetKey; const WidgetRef = ui.WidgetRef; const NodeRef = ui.NodeRef; const WidgetVTable = ui.WidgetVTable; const LayoutSize = ui.LayoutSize; const NullId = ds.CompactNull(u32); const NullFrameId = NullId; const TextMeasure = ui.TextMeasure; pub const TextMeasureId = usize; pub const IntervalId = u32; const log = stdx.log.scoped(.module); pub fn getWidgetIdByType(comptime Widget: type) WidgetTypeId { return @ptrToInt(GenWidgetVTable(Widget)); } /// Generates the vtable for a Widget. pub fn GenWidgetVTable(comptime Widget: type) *const WidgetVTable { const gen = struct { fn create(alloc: std.mem.Allocator, node: *Node, ctx_ptr: *anyopaque, props_ptr: ?[*]const u8) *anyopaque { const ctx = stdx.mem.ptrCastAlign(*InitContext, ctx_ptr); const new: *Widget = if (@sizeOf(Widget) > 0) b: { break :b alloc.create(Widget) catch unreachable; } else undefined; if (@sizeOf(Widget) > 0) { if (comptime WidgetHasProps(Widget)) { if (props_ptr) |props| { const Props = WidgetProps(Widget); new.props = std.mem.bytesToValue(Props, props[0..@sizeOf(Props)]); } } } if (@hasDecl(Widget, "init")) { if (comptime !stdx.meta.hasFunctionSignature(fn (*Widget, *InitContext) void, @TypeOf(Widget.init))) { @compileError("Invalid init function: " ++ @typeName(@TypeOf(Widget.init)) ++ " Widget: " ++ @typeName(Widget)); } // Call widget's init to set state. new.init(ctx); } // Set bind. if (node.bind) |bind| { stdx.mem.ptrCastAlign(*WidgetRef(Widget), bind).* = WidgetRef(Widget).init(node); } if (@sizeOf(Widget) > 0) { return new; } else { // Use a dummy pointer when size = 0. var dummy: bool = undefined; return &dummy; } } fn postInit(widget_ptr: *anyopaque, ctx_ptr: *anyopaque) void { const ctx = stdx.mem.ptrCastAlign(*InitContext, ctx_ptr); const widget = stdx.mem.ptrCastAlign(*Widget, widget_ptr); if (@hasDecl(Widget, "postInit")) { if (comptime !stdx.meta.hasFunctionSignature(fn (*Widget, *InitContext) void, @TypeOf(Widget.postInit))) { @compileError("Invalid postInit function: " ++ @typeName(@TypeOf(Widget.postInit)) ++ " Widget: " ++ @typeName(Widget)); } if (@sizeOf(Widget) == 0) { const empty: *Widget = undefined; empty.postInit(ctx); } else { widget.postInit(ctx); } } } fn updateProps(widget_ptr: *anyopaque, props_ptr: [*]const u8) void { const widget = stdx.mem.ptrCastAlign(*Widget, widget_ptr); if (comptime WidgetHasProps(Widget)) { const Props = WidgetProps(Widget); widget.props = std.mem.bytesToValue(Props, props_ptr[0..@sizeOf(Props)]); } if (@hasDecl(Widget, "postPropsUpdate")) { if (comptime !stdx.meta.hasFunctionSignature(fn (*Widget) void, @TypeOf(Widget.postPropsUpdate))) { @compileError("Invalid postPropsUpdate function: " ++ @typeName(@TypeOf(Widget.postPropsUpdate)) ++ " Widget: " ++ @typeName(Widget)); } widget.postPropsUpdate(); } } fn postUpdate(node: *Node) void { if (@hasDecl(Widget, "postUpdate")) { if (comptime !stdx.meta.hasFunctionSignature(fn (*Node) void, @TypeOf(Widget.postUpdate))) { @compileError("Invalid postUpdate function: " ++ @typeName(@TypeOf(Widget.postUpdate)) ++ " Widget: " ++ @typeName(Widget)); } Widget.postUpdate(node); } } fn build(widget_ptr: *anyopaque, ctx_ptr: *anyopaque) FrameId { const ctx = stdx.mem.ptrCastAlign(*BuildContext, ctx_ptr); const widget = stdx.mem.ptrCastAlign(*Widget, widget_ptr); if (!@hasDecl(Widget, "build")) { // No build function. Return null child. return NullFrameId; } else { if (comptime !stdx.meta.hasFunctionSignature(fn (*Widget, *BuildContext) FrameId, @TypeOf(Widget.build))) { @compileError("Invalid build function: " ++ @typeName(@TypeOf(Widget.build)) ++ " Widget: " ++ @typeName(Widget)); } } if (@sizeOf(Widget) == 0) { const empty: *Widget = undefined; return empty.build(ctx); } else { return widget.build(ctx); } } fn render(node: *Node, ctx: *RenderContext, parent_abs_x: f32, parent_abs_y: f32) void { // Attach node to ctx. ctx.node = node; // Update node's absolute position based on it's relative position and the parent. node.abs_pos = .{ .x = parent_abs_x + node.layout.x, .y = parent_abs_y + node.layout.y, }; if (@hasDecl(Widget, "renderCustom")) { if (comptime !stdx.meta.hasFunctionSignature(fn (*Widget, *RenderContext) void, @TypeOf(Widget.renderCustom))) { @compileError("Invalid renderCustom function: " ++ @typeName(@TypeOf(Widget.renderCustom)) ++ " Widget: " ++ @typeName(Widget)); } if (@sizeOf(Widget) == 0) { const empty: *Widget = undefined; empty.renderCustom(ctx); } else { const widget = stdx.mem.ptrCastAlign(*Widget, node.widget); widget.renderCustom(ctx); } } else if (@hasDecl(Widget, "render")) { if (comptime !stdx.meta.hasFunctionSignature(fn (*Widget, *RenderContext) void, @TypeOf(Widget.render))) { @compileError("Invalid render function: " ++ @typeName(@TypeOf(Widget.render)) ++ " Widget: " ++ @typeName(Widget)); } if (@sizeOf(Widget) == 0) { const empty: *Widget = undefined; empty.render(ctx); } else { const widget = stdx.mem.ptrCastAlign(*Widget, node.widget); widget.render(ctx); } ui_render.defaultRenderChildren(node, ctx); } else { ui_render.defaultRenderChildren(node, ctx); } } fn layout(widget_ptr: *anyopaque, ctx_ptr: *anyopaque) LayoutSize { const ctx = stdx.mem.ptrCastAlign(*LayoutContext, ctx_ptr); const widget = stdx.mem.ptrCastAlign(*Widget, widget_ptr); if (@hasDecl(Widget, "layout")) { if (comptime !stdx.meta.hasFunctionSignature(fn (*Widget, *LayoutContext) LayoutSize, @TypeOf(Widget.layout))) { @compileError("Invalid layout function: " ++ @typeName(@TypeOf(Widget.layout)) ++ " Widget: " ++ @typeName(Widget)); } if (@sizeOf(Widget) == 0) { const empty: *Widget = undefined; return empty.layout(ctx); } else { return widget.layout(ctx); } } else { return defaultLayout(ctx); } } /// The default layout behavior is to report the same size as it's children. /// Multiple children are stacked over each other like a ZStack. fn defaultLayout(c: *LayoutContext) LayoutSize { var max_width: f32 = 0; var max_height: f32 = 0; for (c.node.children.items) |child| { const child_size = c.computeLayoutInherit(child); c.setLayout(child, Layout.init(0, 0, child_size.width, child_size.height)); if (child_size.width > max_width) { max_width = child_size.width; } if (child_size.height > max_height) { max_height = child_size.height; } } return LayoutSize.init(max_width, max_height); } fn destroy(node: *Node, alloc: std.mem.Allocator) void { if (@sizeOf(Widget) > 0) { const widget = stdx.mem.ptrCastAlign(*Widget, node.widget); if (@hasDecl(Widget, "deinit")) { Widget.deinit(node, alloc); } alloc.destroy(widget); } } const vtable = WidgetVTable{ .create = create, .postInit = postInit, .updateProps = updateProps, .postUpdate = postUpdate, .build = build, .render = render, .layout = layout, .destroy = destroy, .has_post_update = @hasDecl(Widget, "postUpdate"), .name = @typeName(Widget), }; }; return &gen.vtable; } pub fn Event(comptime EventType: type) type { return struct { ctx: *EventContext, val: EventType, }; } const FragmentVTable = GenWidgetVTable(struct {}); pub const Module = struct { const Self = @This(); // TODO: Provide widget id map at the root level. alloc: std.mem.Allocator, root_node: ?*Node, user_root: NodeRef, init_ctx: InitContext, build_ctx: BuildContext, layout_ctx: LayoutContext, render_ctx: RenderContext, event_ctx: EventContext, mod_ctx: ModuleContext, common: ModuleCommon, text_measure_batch_buf: std.ArrayList(*graphics.TextMeasure), pub fn init( self: *Self, alloc: std.mem.Allocator, g: *Graphics, ) void { self.* = .{ .alloc = alloc, .root_node = null, .user_root = .{}, .init_ctx = InitContext.init(self), .build_ctx = undefined, .layout_ctx = LayoutContext.init(self, g), .event_ctx = EventContext.init(self), .render_ctx = undefined, .mod_ctx = ModuleContext.init(self), .common = undefined, .text_measure_batch_buf = std.ArrayList(*graphics.TextMeasure).init(alloc), }; self.common.init(alloc, self, g); self.build_ctx = BuildContext.init(alloc, self.common.arena_alloc, self); self.render_ctx = RenderContext.init(&self.common.ctx, g); } pub fn deinit(self: *Self) void { self.build_ctx.deinit(); self.text_measure_batch_buf.deinit(); // Destroy widget nodes. if (self.root_node != null) { const S = struct { fn visit(mod: *Self, node: *Node) void { mod.destroyNode(node); } }; const walker = stdx.algo.recursive.ChildArrayListWalker(*Node); stdx.algo.recursive.walkPost(*Self, self, *Node, self.root_node.?, walker, S.visit); } self.common.deinit(); } pub fn setContextProvider(self: *Self, provider: fn (key: u32) ?*anyopaque) void { self.common.context_provider = provider; } /// Attaches handlers to the event dispatcher. pub fn addInputHandlers(self: *Self, dispatcher: *EventDispatcher) void { const S = struct { fn onKeyDown(ctx: ?*anyopaque, e: platform.KeyDownEvent) void { const self_ = stdx.mem.ptrCastAlign(*Self, ctx); self_.processKeyDownEvent(e); } fn onKeyUp(ctx: ?*anyopaque, e: platform.KeyUpEvent) void { const self_ = stdx.mem.ptrCastAlign(*Self, ctx); self_.processKeyUpEvent(e); } fn onMouseDown(ctx: ?*anyopaque, e: platform.MouseDownEvent) platform.EventResult { const self_ = stdx.mem.ptrCastAlign(*Self, ctx); return self_.processMouseDownEvent(e); } fn onMouseUp(ctx: ?*anyopaque, e: platform.MouseUpEvent) void { const self_ = stdx.mem.ptrCastAlign(*Self, ctx); self_.processMouseUpEvent(e); } fn onMouseScroll(ctx: ?*anyopaque, e: platform.MouseScrollEvent) void { const self_ = stdx.mem.ptrCastAlign(*Self, ctx); self_.processMouseScrollEvent(e); } fn onMouseMove(ctx: ?*anyopaque, e: platform.MouseMoveEvent) void { const self_ = stdx.mem.ptrCastAlign(*Self, ctx); self_.processMouseMoveEvent(e); } }; dispatcher.addOnKeyDown(self, S.onKeyDown); dispatcher.addOnKeyUp(self, S.onKeyUp); dispatcher.addOnMouseDown(self, S.onMouseDown); dispatcher.addOnMouseUp(self, S.onMouseUp); dispatcher.addOnMouseScroll(self, S.onMouseScroll); dispatcher.addOnMouseMove(self, S.onMouseMove); } pub fn getUserRoot(self: Self, comptime Widget: type) ?*Widget { if (self.root_node != null) { const root = self.root_node.?.getWidget(ui.widgets.Root); if (root.user_root.binded) { return root.user_root.node.getWidget(Widget); } } return null; } fn getWidget(self: *Self, comptime Widget: type, node: *Node) *Widget { _ = self; return stdx.mem.ptrCastAlign(*Widget, node.widget); } pub fn processMouseUpEvent(self: *Self, e: platform.MouseUpEvent) void { const xf = @intToFloat(f32, e.x); const yf = @intToFloat(f32, e.y); self.common.last_focused_widget = self.common.focused_widget; self.common.hit_last_focused = false; // Trigger global handlers first. for (self.common.global_mouse_up_list.items) |id| { const sub = self.common.mouse_up_event_subs.getNoCheck(id); const node = sub.sub.node; if (node == self.common.last_focused_widget) { self.common.hit_last_focused = true; } self.event_ctx.node = node; sub.sub.handleEvent(&self.event_ctx, e); } // Greedy hit test starting from the root. if (self.root_node) |node| { _ = self.processMouseUpEventRecurse(node, xf, yf, e); } if (self.common.last_focused_widget != null and self.common.last_focused_widget == self.common.focused_widget and !self.common.hit_last_focused) { self.common.focused_onblur(self.common.focused_widget.?, &self.common.ctx); self.common.focused_widget = null; self.common.focused_onblur = undefined; } } fn processMouseUpEventRecurse(self: *Self, node: *Node, xf: f32, yf: f32, e: platform.MouseUpEvent) bool { const pos = node.abs_pos; if (xf >= pos.x and xf <= pos.x + node.layout.width and yf >= pos.y and yf <= pos.y + node.layout.height) { if (node == self.common.last_focused_widget) { self.common.hit_last_focused = true; } var cur = node.mouse_up_list; while (cur != NullId) { const sub = self.common.mouse_up_event_subs.getNoCheck(cur); if (!sub.is_global) { sub.sub.handleEvent(&self.event_ctx, e); cur = self.common.mouse_up_event_subs.getNextNoCheck(cur); } } const event_children = if (!node.has_child_event_ordering) node.children.items else node.child_event_ordering; for (event_children) |child| { if (self.processMouseUpEventRecurse(child, xf, yf, e)) { break; } } return true; } else return false; } /// Start at the root node and propagate downwards on the first hit box. /// TODO: Handlers should be able to return Stop to prevent propagation. pub fn processMouseDownEvent(self: *Self, e: platform.MouseDownEvent) platform.EventResult { const xf = @intToFloat(f32, e.x); const yf = @intToFloat(f32, e.y); self.common.last_focused_widget = self.common.focused_widget; self.common.hit_last_focused = false; var hit_widget = false; if (self.root_node) |node| { _ = self.processMouseDownEventRecurse(node, xf, yf, e, &hit_widget); } // If the existing focused widget wasn't hit and no other widget requested focus, trigger blur. if (self.common.last_focused_widget != null and self.common.last_focused_widget == self.common.focused_widget and !self.common.hit_last_focused) { self.common.focused_onblur(self.common.focused_widget.?, &self.common.ctx); self.common.focused_widget = null; self.common.focused_onblur = undefined; } if (hit_widget) { return .Stop; } else { return .Continue; } } fn processMouseDownEventRecurse(self: *Self, node: *Node, xf: f32, yf: f32, e: platform.MouseDownEvent, hit_widget: *bool) bool { const pos = node.abs_pos; if (xf >= pos.x and xf <= pos.x + node.layout.width and yf >= pos.y and yf <= pos.y + node.layout.height) { if (node == self.common.last_focused_widget) { self.common.hit_last_focused = true; hit_widget.* = true; } var cur = node.mouse_down_list; if (cur != NullId) { // If there is a handler, assume the event hits the widget. // If the widget performs clearMouseHitFlag() in any of the handlers, the flag is reset so it does not change hit_widget. self.common.widget_hit_flag = true; } var propagate = true; while (cur != NullId) { const sub = self.common.mouse_down_event_subs.getNoCheck(cur); if (sub.handleEvent(&self.event_ctx, e) == .Stop) { propagate = false; break; } cur = self.common.mouse_down_event_subs.getNextNoCheck(cur); } if (self.common.widget_hit_flag) { hit_widget.* = true; } if (!propagate) { return true; } const event_children = if (!node.has_child_event_ordering) node.children.items else node.child_event_ordering; for (event_children) |child| { if (self.processMouseDownEventRecurse(child, xf, yf, e, hit_widget)) { break; } } return true; } else return false; } pub fn processMouseScrollEvent(self: *Self, e: platform.MouseScrollEvent) void { const xf = @intToFloat(f32, e.x); const yf = @intToFloat(f32, e.y); if (self.root_node) |node| { _ = self.processMouseScrollEventRecurse(node, xf, yf, e); } } fn processMouseScrollEventRecurse(self: *Self, node: *Node, xf: f32, yf: f32, e: platform.MouseScrollEvent) bool { const pos = node.abs_pos; if (xf >= pos.x and xf <= pos.x + node.layout.width and yf >= pos.y and yf <= pos.y + node.layout.height) { var cur = node.mouse_scroll_list; while (cur != NullId) { const sub = self.common.mouse_scroll_event_subs.getNoCheck(cur); sub.handleEvent(&self.event_ctx, e); cur = self.common.mouse_scroll_event_subs.getNextNoCheck(cur); } const event_children = if (!node.has_child_event_ordering) node.children.items else node.child_event_ordering; for (event_children) |child| { if (self.processMouseScrollEventRecurse(child, xf, yf, e)) { break; } } return true; } else return false; } pub fn processMouseMoveEvent(self: *Self, e: platform.MouseMoveEvent) void { for (self.common.mouse_move_event_subs.items) |*it| { it.handleEvent(&self.event_ctx, e); } } pub fn processKeyDownEvent(self: *Self, e: platform.KeyDownEvent) void { // Only the focused widget receives input. if (self.common.focused_widget) |focused_widget| { var cur = focused_widget.key_down_list; while (cur != NullId) { const sub = self.common.key_down_event_subs.getNoCheck(cur); sub.handleEvent(&self.event_ctx, e); cur = self.common.key_down_event_subs.getNextNoCheck(cur); } } } pub fn processKeyUpEvent(self: *Self, e: platform.KeyUpEvent) void { // Only the focused widget receives input. if (self.common.focused_widget) |focused_widget| { var cur = focused_widget.key_up_list; while (cur != NullId) { const sub = self.common.key_up_event_subs.getNoCheck(cur); sub.handleEvent(&self.event_ctx, e); cur = self.common.key_up_event_subs.getNextNoCheck(cur); } } } fn updateRoot(self: *Self, root_id: FrameId) !void { if (root_id != NullFrameId) { const root = self.build_ctx.getFrame(root_id); if (self.root_node) |root_node| { if (root_node.vtable == root.vtable) { try self.updateExistingNode(null, root_id, root_node); } else { self.removeNode(root_node); // Create the node first so getRoot() works in `init` and `postInit` callbacks. var new_node = self.alloc.create(Node) catch unreachable; self.root_node = new_node; errdefer self.root_node = null; _ = try self.createAndUpdateNode2(null, root_id, 0, new_node); } } else { var new_node = self.alloc.create(Node) catch unreachable; self.root_node = new_node; errdefer self.root_node = null; _ = try self.createAndUpdateNode2(null, root_id, 0, new_node); } } else { if (self.root_node) |root_node| { // Remove existing root. self.removeNode(root_node); self.root_node = null; } } } // 1. Run timers/intervals/animations. // 2. Build frames. Diff tree and create/update nodes from frames. // 3. Compute layout. // 4. Run next post layout cbs. pub fn preUpdate(self: *Self, delta_ms: f32, bootstrap_ctx: anytype, comptime bootstrap_fn: fn (@TypeOf(bootstrap_ctx), *BuildContext) FrameId, layout_size: LayoutSize) UpdateError!void { self.common.updateIntervals(delta_ms, &self.event_ctx); // TODO: check if we have to update // Reset the builder buffer before we call any Component.build self.build_ctx.resetBuffer(); self.common.arena_allocator.deinit(); self.common.arena_allocator.state = .{}; // TODO: Provide a different context for the bootstrap function since it doesn't have a frame or node. Currently uses the BuildContext. self.build_ctx.prepareCall(undefined, undefined); const user_root_id = bootstrap_fn(bootstrap_ctx, &self.build_ctx); if (user_root_id != NullFrameId) { const user_root = self.build_ctx.getFrame(user_root_id); if (user_root.vtable == FragmentVTable) { return error.UserRootCantBeFragment; } } // The user root widget is wrapped by the Root widget to facilitate things like modals and popovers. const root_id = self.build_ctx.decl(ui.widgets.Root, .{ .user_root = user_root_id }); // Since the aim is to do layout in linear time, the tree should be built first. // Traverse to see which nodes need to be created/deleted. try self.updateRoot(root_id); // Before computing layout, perform batched measure text. // Widgets can still explicitly measure text so the purpose of this is to act as a placeholder for future work to speed up text measurements. self.text_measure_batch_buf.clearRetainingCapacity(); var iter = self.common.text_measures.iterator(); while (iter.nextPtr()) |measure| { self.text_measure_batch_buf.append(&measure.measure) catch unreachable; } self.common.g.measureTextBatch(self.text_measure_batch_buf.items); // Compute layout only after all widgets/nodes exist since // only the Widget knows how to compute it's layout and that could depend on state and nested child nodes. // The goal here is to perform layout in linear time, more specifically pre and post visits to each node. if (self.root_node != null) { const size = self.layout_ctx.computeLayout(self.root_node.?, layout_size); self.layout_ctx.setLayout(self.root_node.?, Layout.init(0, 0, size.width, size.height)); } // Run logic that needs to happen after layout. for (self.common.next_post_layout_cbs.items) |*it| { it.call(.{}); it.deinit(self.alloc); } self.common.next_post_layout_cbs.clearRetainingCapacity(); } pub fn postUpdate(self: *Self) void { _ = self; // TODO: defer destroying widgets so that callbacks don't reference stale data. } /// Update a full app frame. Parts of the update are split up to facilitate testing. /// A bootstrap fn is needed to tell the module how to build the root frame. /// A width and height is needed to specify the root container size in which subsequent widgets will use for layout. pub fn updateAndRender(self: *Self, delta_ms: f32, bootstrap_ctx: anytype, comptime bootstrap_fn: fn (@TypeOf(bootstrap_ctx), *BuildContext) FrameId, width: f32, height: f32) !void { const layout_size = LayoutSize.init(width, height); try self.preUpdate(delta_ms, bootstrap_ctx, bootstrap_fn, layout_size); self.render(delta_ms); self.postUpdate(); } /// Just do an update without rendering. pub fn update(self: *Self, delta_ms: f32, bootstrap_ctx: anytype, comptime bootstrap_fn: fn (@TypeOf(bootstrap_ctx), *BuildContext) FrameId, width: f32, height: f32) !void { const layout_size = LayoutSize.init(width, height); try self.preUpdate(delta_ms, bootstrap_ctx, bootstrap_fn, layout_size); self.postUpdate(); } pub fn render(self: *Self, delta_ms: f32) void { self.render_ctx.delta_ms = delta_ms; ui_render.render(self); } /// Assumes the widget and the frame represent the same instance, /// so the widget is updated with the frame's props. /// Recursively update children. /// This assumes the frame's key is equal to the node's key. fn updateExistingNode(self: *Self, parent: ?*Node, frame_id: FrameId, node: *Node) UpdateError!void { _ = parent; // Update frame and props. const frame = self.build_ctx.getFrame(frame_id); // if (parent) |pn| { // node.transform = pn.transform; // } const widget_vtable = frame.vtable; if (frame.props.len > 0) { const props_ptr = self.build_ctx.frame_props.getBytesPtr(frame.props); widget_vtable.updateProps(node.widget, props_ptr); } defer { if (widget_vtable.has_post_update) { widget_vtable.postUpdate(node); } } const child_frame_id = self.buildChildFrame(frame_id, node, widget_vtable); if (child_frame_id == NullId) { if (node.children.items.len > 0) { for (node.children.items) |it| { self.removeNode(it); } } node.children.items.len = 0; return; } const child_frame = self.build_ctx.getFrame(child_frame_id); if (child_frame.vtable == FragmentVTable) { // Fragment frame, diff it's children instead. const child_frames = child_frame.fragment_children; // Start by doing fast array iteration to update nodes with the same key/idx. // Once there is a discrepancy, switch to the slower method of key map checks. var child_idx: u32 = 0; while (child_idx < child_frames.len) : (child_idx += 1) { const child_id = self.build_ctx.frame_lists.items[child_frames.id + child_idx]; const child_frame_ = self.build_ctx.getFrame(child_id); if (child_frame_.vtable == FragmentVTable) { return error.NestedFragment; } if (node.children.items.len <= child_idx) { // TODO: Create nodes for the rest of the frames instead. try self.updateChildFramesWithKeyMap(node, child_idx, child_frames); return; } const child_node = node.children.items[child_idx]; if (child_node.vtable != child_frame_.vtable) { try self.updateChildFramesWithKeyMap(node, child_idx, child_frames); return; } const frame_key = if (child_frame_.key != null) child_frame_.key.? else WidgetKey{.Idx = child_idx}; if (!std.meta.eql(child_node.key, frame_key)) { try self.updateChildFramesWithKeyMap(node, child_idx, child_frames); return; } try self.updateExistingNode(node, child_id, child_node); } // Remove left over children. if (child_idx < node.children.items.len) { for (node.children.items[child_idx..]) |it| { self.removeNode(it); } node.children.items.len = child_frames.len; } } else { // One child frame. if (node.children.items.len == 0) { const new_child = try self.createAndUpdateNode(node, child_frame_id, 0); node.children.append(new_child) catch unreachable; return; } const child_node = node.children.items[0]; if (child_node.vtable != child_frame.vtable) { self.removeNode(child_node); const new_child = try self.createAndUpdateNode(node, child_frame_id, 0); node.children.items[0] = new_child; if (node.children.items.len > 1) { for (node.children.items[1..]) |it| { self.removeNode(it); } } return; } const frame_key = if (child_frame.key != null) child_frame.key.? else WidgetKey{.Idx = 0}; if (!std.meta.eql(child_node.key, frame_key)) { self.removeNode(child_node); const new_child = try self.createAndUpdateNode(node, child_frame_id, 0); node.children.items[0] = new_child; if (node.children.items.len > 1) { for (node.children.items[1..]) |it| { self.removeNode(it); } } return; } // Same child. try self.updateExistingNode(node, child_frame_id, child_node); } } /// Slightly slower method to update with frame children that utilizes a key map. fn updateChildFramesWithKeyMap(self: *Self, parent: *Node, start_idx: u32, child_frames: FrameListPtr) UpdateError!void { var child_idx: u32 = start_idx; while (child_idx < child_frames.len): (child_idx += 1) { const frame_id = self.build_ctx.frame_lists.items[child_frames.id + child_idx]; const frame = self.build_ctx.getFrame(frame_id); if (frame.vtable == FragmentVTable) { return error.NestedFragment; } const frame_key = if (frame.key != null) frame.key.? else WidgetKey{.Idx = child_idx}; // Look for an existing child by key. const existing_node_q = parent.key_to_child.get(frame_key); if (existing_node_q != null and existing_node_q.?.vtable == frame.vtable) { try self.updateExistingNode(parent, frame_id, existing_node_q.?); // Update the children list as we iterate. if (parent.children.items[child_idx] != existing_node_q.?) { // Move the unused item to the end so we can delete them afterwards. parent.children.append(parent.children.items[child_idx]) catch unreachable; } parent.children.items[child_idx] = existing_node_q.?; } else { if (parent.children.items.len == child_idx) { // Exceeded the size of the existing children list. Insert the rest from child frames. const new_child = try self.createAndUpdateNode(parent, frame_id, child_idx); parent.children.append(new_child) catch unreachable; child_idx += 1; while (child_idx < child_frames.len) : (child_idx += 1) { const frame_id_ = self.build_ctx.frame_lists.items[child_frames.id + child_idx]; const new_child_ = try self.createAndUpdateNode(parent, frame_id_, child_idx); parent.children.append(new_child_) catch unreachable; } break; } if (parent.children.items.len > child_idx) { // Move the child at the same idx to the end. parent.children.append(parent.children.items[child_idx]) catch unreachable; } // Create a new child instance to correspond with child frame. const new_child = try self.createAndUpdateNode(parent, frame_id, child_idx); parent.children.items[child_idx] = new_child; } } // All the unused children were moved to the end so we can delete them all. // TODO: deal with different instances with the same key. for (parent.children.items[child_idx..]) |it| { self.removeNode(it); } // Truncate existing children list to frame children list. if (parent.children.items.len > child_frames.len) { parent.children.shrinkRetainingCapacity(child_frames.len); } } /// Removes the node and performs deinit but does not unlink from the parent.children array since it's expensive. /// Assumes the caller has delt with it. fn removeNode(self: *Self, node: *Node) void { // Remove children first. for (node.children.items) |child| { self.removeNode(child); } if (node.parent != null) { _ = node.parent.?.key_to_child.remove(node.key); } self.destroyNode(node); } fn destroyNode(self: *Self, node: *Node) void { if (node.has_widget_id) { if (self.common.id_map.get(node.id)) |val| { // Must check that this node currently maps to that id since node removal can happen after newly created node. if (val == node) { _ = self.common.id_map.remove(node.id); } } } const widget_vtable = node.vtable; widget_vtable.destroy(node, self.alloc); // Make sure event handlers are removed. var cur_id = node.key_up_list; while (cur_id != NullId) { const sub = self.common.key_up_event_subs.getNoCheck(cur_id); sub.deinit(self.alloc); self.common.key_up_event_subs.removeAssumeNoPrev(cur_id) catch unreachable; cur_id = self.common.key_up_event_subs.getNextNoCheck(cur_id); } cur_id = node.key_down_list; while (cur_id != NullId) { const sub = self.common.key_down_event_subs.getNoCheck(cur_id); sub.deinit(self.alloc); self.common.key_down_event_subs.removeAssumeNoPrev(cur_id) catch unreachable; cur_id = self.common.key_down_event_subs.getNextNoCheck(cur_id); } cur_id = node.mouse_down_list; while (cur_id != NullId) { const sub = self.common.mouse_down_event_subs.getNoCheck(cur_id); sub.deinit(self.alloc); self.common.mouse_down_event_subs.removeAssumeNoPrev(cur_id) catch unreachable; cur_id = self.common.mouse_down_event_subs.getNextNoCheck(cur_id); } cur_id = node.mouse_up_list; while (cur_id != NullId) { const sub = self.common.mouse_up_event_subs.getNoCheck(cur_id); sub.sub.deinit(self.alloc); self.common.mouse_up_event_subs.removeAssumeNoPrev(cur_id) catch unreachable; cur_id = self.common.mouse_up_event_subs.getNextNoCheck(cur_id); } var i = @intCast(u32, self.common.mouse_move_event_subs.items.len); // TODO: Make faster. while (i > 0) { i -= 1; if (self.common.mouse_move_event_subs.items[i].node == node) { self.common.mouse_move_event_subs.items[i].deinit(self.alloc); _ = self.common.mouse_move_event_subs.orderedRemove(i); } } // TODO: Make faster. var iter = self.common.interval_sessions.iterator(); while (iter.next()) |it| { if (it.node == node) { it.deinit(self.alloc); self.common.interval_sessions.remove(iter.cur_id); } } // Check that the focused widget is still valid. if (self.common.focused_widget) |focused| { if (focused == node) { self.common.focused_widget = null; } } node.deinit(); self.alloc.destroy(node); } /// Builds the child frame for a given frame. fn buildChildFrame(self: *Self, frame_id: FrameId, node: *Node, widget_vtable: *const WidgetVTable) FrameId { self.build_ctx.prepareCall(frame_id, node); return widget_vtable.build(node.widget, &self.build_ctx); } inline fn createAndUpdateNode(self: *Self, parent: ?*Node, frame_id: FrameId, idx: u32) UpdateError!*Node { const new_node = self.alloc.create(Node) catch unreachable; return self.createAndUpdateNode2(parent, frame_id, idx, new_node); } /// Allow passing in a new node so a ref can be obtained beforehand. fn createAndUpdateNode2(self: *Self, parent: ?*Node, frame_id: FrameId, idx: u32, new_node: *Node) UpdateError!*Node { const frame = self.build_ctx.getFrame(frame_id); const widget_vtable = frame.vtable; errdefer { for (new_node.children.items) |child| { self.destroyNode(child); } self.destroyNode(new_node); } const props_ptr = if (frame.props.len > 0) self.build_ctx.frame_props.getBytesPtr(frame.props) else null; // Init instance. // log.warn("create node {}", .{frame.type_id}); const key = if (frame.key != null) frame.key.? else WidgetKey{.Idx = idx}; new_node.init(self.alloc, frame.vtable, parent, key, undefined); if (frame.id) |id| { // Due to how diffing works, nodes are batched removed at the end so a new node could be created to replace an existing one and still run into an id collision. // For now, just overwrite the existing mapping and make sure node removal only removes the id mapping if the entry matches the node. self.common.id_map.put(id, new_node) catch @panic("error"); new_node.id = id; new_node.has_widget_id = true; } new_node.bind = frame.widget_bind; if (parent != null) { parent.?.key_to_child.put(key, new_node) catch unreachable; } self.init_ctx.prepareForNode(new_node); const new_widget = widget_vtable.create(self.alloc, new_node, &self.init_ctx, props_ptr); new_node.widget = new_widget; if (frame.node_binds != null) { var mb_cur = frame.node_binds; while (mb_cur) |cur| { cur.node_ref.* = NodeRef.init(new_node); mb_cur = cur.next; } } //log.warn("created: {}", .{frame.type_id}); // Build child frames and create child nodes from them. const child_frame_id = self.buildChildFrame(frame_id, new_node, widget_vtable); if (child_frame_id != NullId) { const child_frame = self.build_ctx.getFrame(child_frame_id); if (child_frame.vtable == FragmentVTable) { // Fragment frame. const child_frames = child_frame.fragment_children; // Iterate using a counter since the frame list buffer is dynamic. var child_idx: u32 = 0; while (child_idx < child_frames.len) : (child_idx += 1) { const child_id = self.build_ctx.frame_lists.items[child_frames.id + child_idx]; const child_frame_ = self.build_ctx.getFrame(child_id); if (child_frame_.vtable == FragmentVTable) { return error.NestedFragment; } const child_node = try self.createAndUpdateNode(new_node, child_id, child_idx); new_node.children.append(child_node) catch unreachable; } } else { // Single child frame. const child_node = try self.createAndUpdateNode(new_node, child_frame_id, 0); new_node.children.append(child_node) catch unreachable; } } // log.debug("after {s}", .{getWidgetName(frame.type_id)}); self.init_ctx.prepareForNode(new_node); widget_vtable.postInit(new_widget, &self.init_ctx); return new_node; } pub fn dumpTree(self: Self) void { if (self.root_node) |root| { dumpTreeR(self, 0, root); } } fn dumpTreeR(self: Self, depth: u32, node: *Node) void { var foo: [100]u8 = undefined; std.mem.set(u8, foo[0..depth*2], ' '); log.debug("{s}{s}", .{ foo[0..depth*2], node.vtable.name }); for (node.children.items) |child| { self.dumpTreeR(depth + 1, child); } } }; pub const RenderContext = struct { common: *CommonContext, g: *Graphics, /// Elapsed time since the last render. delta_ms: f32, // Current node. node: *Node, const Self = @This(); fn init(common: *CommonContext, g: *Graphics) Self { return .{ .g = g, .common = common, .node = undefined, .delta_ms = 0, }; } /// Note that this will update the current RenderContext. /// If you need RenderContext.node afterwards, that should be stored in a local variable first. /// To help prevent the user from forgetting this, an explicit parent_node is required. pub inline fn renderChildNode(self: *Self, parent: *Node, node: *Node) void { node.vtable.render(node, self, parent.abs_pos.x, parent.abs_pos.y); } /// Renders the children in order. pub inline fn renderChildren(self: *Self) void { const parent = self.node; for (self.node.children.items) |child| { child.vtable.render(child, self, parent.abs_pos.x, parent.abs_pos.y); } } pub inline fn getAbsLayout(self: *Self) Layout { return self.node.getAbsLayout(); } pub inline fn getGraphics(self: *Self) *Graphics { return self.g; } pub usingnamespace MixinContextNodeReadOps(Self); // pub usingnamespace MixinContextReadOps(Self); }; fn IntervalHandler(comptime Context: type) type { return fn (Context, IntervalEvent) void; } /// Requires Context.common. pub fn MixinContextEventOps(comptime Context: type) type { return struct { pub inline fn resetInterval(self: *Context, id: IntervalId) void { self.common.resetInterval(id); } pub inline fn removeInterval(self: *Context, id: IntervalId) void { self.common.removeInterval(id); } }; } /// Requires Context.common. pub fn MixinContextSharedOps(comptime Context: type) type { return struct { pub inline fn getContext(self: Context, key: u32) ?*anyopaque { return self.common.common.context_provider(key); } pub inline fn getGraphics(self: Context) *graphics.Graphics { return self.common.getGraphics(); } pub inline fn getRoot(self: Context) *ui.widgets.Root { return self.common.common.mod.root_node.?.getWidget(ui.widgets.Root); } }; } /// Requires Context.common. pub fn MixinContextFontOps(comptime Context: type) type { return struct { pub inline fn getFontVMetrics(self: Context, font_id: FontId, font_size: f32) graphics.VMetrics { return self.common.getFontVMetrics(font_id, font_size); } pub inline fn getPrimaryFontVMetrics(self: Context, font_gid: FontGroupId, font_size: f32) graphics.VMetrics { return self.common.getPrimaryFontVMetrics(font_gid, font_size); } pub inline fn getTextMeasure(self: Context, id: TextMeasureId) *TextMeasure { return self.common.getTextMeasure(id); } pub inline fn measureText(self: *Context, font_gid: FontGroupId, font_size: f32, str: []const u8) graphics.TextMetrics { return self.common.measureText(font_gid, font_size, str); } pub inline fn textGlyphIter(self: *Context, font_gid: FontGroupId, font_size: f32, str: []const u8) graphics.TextGlyphIterator { return self.common.textGlyphIter(font_gid, font_size, str); } pub inline fn textLayout(self: *Context, font_gid: FontGroupId, font_size: f32, str: []const u8, max_width: f32, buf: *graphics.TextLayout) void { return self.common.textLayout(font_gid, font_size, str, max_width, buf); } pub inline fn getFontGroupBySingleFontName(self: Context, name: []const u8) FontGroupId { return self.common.getFontGroupBySingleFontName(name); } pub inline fn getFontGroupByFamily(self: Context, family: graphics.FontFamily) FontGroupId { return self.common.getFontGroupByFamily(family); } pub inline fn getFontGroupForSingleFont(self: Context, font_id: FontId) FontGroupId { return self.common.getFontGroupForSingleFont(font_id); } pub inline fn getFontGroupForSingleFontOrDefault(self: Context, font_id: FontId) FontGroupId { if (font_id == NullId) { return self.getDefaultFontGroup(); } else { return self.common.getFontGroupForSingleFont(font_id); } } pub inline fn getDefaultFontGroup(self: Context) FontGroupId { return self.common.getDefaultFontGroup(); } pub inline fn createTextMeasure(self: *Context, font_gid: FontGroupId, font_size: f32) TextMeasureId { return self.common.createTextMeasure(font_gid, font_size); } }; } const BlurHandler = fn (node: *Node, ctx: *CommonContext) void; /// Ops that make sense with an attached node. /// Requires Context.node and Context.common. pub fn MixinContextNodeOps(comptime Context: type) type { return struct { pub inline fn getNode(self: *Context) *Node { return self.node; } pub inline fn requestFocus(self: *Context, on_blur: BlurHandler) void { self.common.requestFocus(self.node, on_blur); } pub inline fn requestCaptureMouse(self: *Context, capture: bool) void { self.common.requestCaptureMouse(capture); } pub inline fn addInterval(self: *Context, dur: Duration, ctx: anytype, cb: IntervalHandler(@TypeOf(ctx))) IntervalId { return self.common.addInterval(self.node, dur, ctx, cb); } pub inline fn addMouseUpHandler(self: *Context, ctx: anytype, cb: MouseUpHandler(@TypeOf(ctx))) void { self.common.addMouseUpHandler(self.node, ctx, cb); } pub inline fn addGlobalMouseUpHandler(self: *Context, ctx: anytype, cb: MouseUpHandler(@TypeOf(ctx))) void { self.common.addGlobalMouseUpHandler(self.node, ctx, cb); } pub inline fn addMouseDownHandler(self: Context, ctx: anytype, cb: MouseDownHandler(@TypeOf(ctx))) void { self.common.addMouseDownHandler(self.node, ctx, cb); } pub inline fn addMouseScrollHandler(self: Context, ctx: anytype, cb: MouseScrollHandler(@TypeOf(ctx))) void { self.common.addMouseScrollHandler(self.node, ctx, cb); } pub inline fn addKeyDownHandler(self: *Context, ctx: anytype, cb: KeyDownHandler(@TypeOf(ctx))) void { self.common.addKeyDownHandler(self.node, ctx, cb); } pub inline fn addKeyUpHandler(self: *Context, ctx: anytype, cb: KeyUpHandler(@TypeOf(ctx))) void { self.common.addKeyUpHandler(self.node, ctx, cb); } pub inline fn addMouseMoveHandler(self: *Context, ctx: anytype, cb: MouseMoveHandler(@TypeOf(ctx))) void { self.common.addMouseMoveHandler(self.node, ctx, cb); } pub inline fn removeMouseUpHandler(self: *Context, comptime Ctx: type, func: MouseUpHandler(Ctx)) void { self.common.removeMouseUpHandler(self.node, Ctx, func); } }; } /// Requires Context.node and Context.common. pub fn MixinContextNodeReadOps(comptime Context: type) type { return struct { pub inline fn isFocused(self: *Context) bool { return self.common.isFocused(self.node); } }; } /// Requires Context.common. pub fn MixinContextInputOps(comptime Context: type) type { return struct { pub inline fn removeKeyUpHandler(self: *Context, comptime Ctx: type, func: KeyUpHandler(Ctx)) void { self.common.removeKeyUpHandler(Ctx, func); } pub inline fn removeMouseMoveHandler(self: *Context, comptime Ctx: type, func: MouseMoveHandler(Ctx)) void { self.common.removeMouseMoveHandler(Ctx, func); } }; } pub const LayoutContext = struct { mod: *Module, common: *CommonContext, g: *Graphics, /// Vars set by parent and consumed by Widget.layout cstr: LayoutSize, node: *Node, /// If this is false, prefer the layout size to not exceed the max layout size equal to cstr. /// If true, either the width, or height, or both prefer an exact value. prefer_exact_width_or_height: bool, prefer_exact_width: bool, prefer_exact_height: bool, const Self = @This(); fn init(mod: *Module, g: *Graphics) Self { return .{ .mod = mod, .common = &mod.common.ctx, .prefer_exact_width_or_height = false, .prefer_exact_width = false, .prefer_exact_height = false, .g = g, .cstr = undefined, .node = undefined, }; } pub inline fn getSizeConstraint(self: Self) LayoutSize { return self.cstr; } /// Computes the layout for a node with a preferred max size. pub fn computeLayout(self: *Self, node: *Node, max_size: LayoutSize) LayoutSize { // Creates another context on the stack so the caller can continue to use their context. var child_ctx = LayoutContext{ .mod = self.mod, .common = &self.mod.common.ctx, .g = self.g, .cstr = max_size, .prefer_exact_width_or_height = false, .prefer_exact_width = false, .prefer_exact_height = false, .node = node, }; return node.vtable.layout(node.widget, &child_ctx); } /// Computes the layout for a node with additional stretch preferences. pub fn computeLayoutStretch(self: *Self, node: *Node, cstr: LayoutSize, prefer_exact_width: bool, prefer_exact_height: bool) LayoutSize { var child_ctx = LayoutContext{ .mod = self.mod, .common = &self.mod.common.ctx, .g = self.g, .cstr = cstr, .prefer_exact_width_or_height = prefer_exact_width or prefer_exact_height, .prefer_exact_width = prefer_exact_width, .prefer_exact_height = prefer_exact_height, .node = node, }; return node.vtable.layout(node.widget, &child_ctx); } pub fn computeLayoutInherit(self: *Self, node: *Node) LayoutSize { var child_ctx = LayoutContext{ .mod = self.mod, .common = &self.mod.common.ctx, .g = self.g, .cstr = self.cstr, .prefer_exact_width_or_height = self.prefer_exact_width_or_height, .prefer_exact_width = self.prefer_exact_width, .prefer_exact_height = self.prefer_exact_height, .node = node, }; return node.vtable.layout(node.widget, &child_ctx); } pub fn setLayout(self: *Self, node: *Node, layout: Layout) void { _ = self; node.layout = layout; } pub fn setLayoutPos(self: *Self, node: *Node, x: f32, y: f32) void { _ = self; node.layout.x = x; node.layout.y = y; } pub inline fn getLayout(self: *Self, node: *Node) Layout { _ = self; return node.layout; } pub usingnamespace MixinContextNodeOps(Self); pub usingnamespace MixinContextFontOps(Self); }; pub const EventContext = struct { alloc: std.mem.Allocator, common: *CommonContext, node: *Node, const Self = @This(); fn init(mod: *Module) Self { return .{ .common = &mod.common.ctx, .alloc = mod.alloc, .node = undefined, }; } pub usingnamespace MixinContextInputOps(Self); pub usingnamespace MixinContextNodeOps(Self); pub usingnamespace MixinContextFontOps(Self); pub usingnamespace MixinContextEventOps(Self); }; pub const KeyDownEvent = Event(platform.KeyDownEvent); pub const KeyUpEvent = Event(platform.KeyUpEvent); pub const MouseDownEvent = Event(platform.MouseDownEvent); pub const MouseUpEvent = Event(platform.MouseUpEvent); pub const MouseMoveEvent = Event(platform.MouseMoveEvent); pub const MouseScrollEvent = Event(platform.MouseScrollEvent); fn KeyDownHandler(comptime Context: type) type { return fn (Context, KeyDownEvent) void; } fn KeyUpHandler(comptime Context: type) type { return fn (Context, KeyUpEvent) void; } fn MouseMoveHandler(comptime Context: type) type { return fn (Context, MouseMoveEvent) void; } fn MouseDownHandler(comptime Context: type) type { return fn (Context, MouseDownEvent) ui.EventResult; } fn MouseUpHandler(comptime Context: type) type { return fn (Context, MouseUpEvent) void; } fn MouseScrollHandler(comptime Context: type) type { return fn (Context, MouseScrollEvent) void; } /// Does not depend on ModuleConfig so it can be embedded into Widget structs to access common utilities. pub const CommonContext = struct { const Self = @This(); common: *ModuleCommon, alloc: std.mem.Allocator, pub inline fn getFontVMetrics(self: Self, font_gid: FontGroupId, font_size: f32) graphics.VMetrics { return self.common.g.getFontVMetrics(font_gid, font_size); } pub inline fn getPrimaryFontVMetrics(self: Self, font_gid: FontGroupId, font_size: f32) graphics.VMetrics { return self.common.g.getPrimaryFontVMetrics(font_gid, font_size); } pub inline fn createTextMeasure(self: *Self, font_gid: FontGroupId, font_size: f32) TextMeasureId { return self.common.createTextMeasure(font_gid, font_size); } pub inline fn destroyTextMeasure(self: *Self, id: TextMeasureId) void { self.mod.destroyTextMeasure(id); } pub fn getTextMeasure(self: Self, id: TextMeasureId) *TextMeasure { return self.common.getTextMeasure(id); } pub fn measureText(self: *Self, font_gid: FontGroupId, font_size: f32, str: []const u8) graphics.TextMetrics { var res: graphics.TextMetrics = undefined; self.common.g.measureFontText(font_gid, font_size, str, &res); return res; } pub inline fn textGlyphIter(self: *Self, font_gid: FontGroupId, font_size: f32, str: []const u8) graphics.TextGlyphIterator { return self.common.g.textGlyphIter(font_gid, font_size, str); } pub inline fn textLayout(self: *Self, font_gid: FontGroupId, font_size: f32, str: []const u8, max_width: f32, buf: *graphics.TextLayout) void { self.common.g.textLayout(font_gid, font_size, str, max_width, buf); } pub inline fn getFontGroupForSingleFont(self: Self, font_id: FontId) FontGroupId { return self.common.g.getFontGroupForSingleFont(font_id); } pub inline fn getFontGroupForSingleFontOrDefault(self: Self, font_id: FontId) FontGroupId { if (font_id == NullId) { return self.getDefaultFontGroup(); } else { return self.getFontGroupForSingleFont(font_id); } } pub inline fn getFontGroupBySingleFontName(self: Self, name: []const u8) FontGroupId { return self.common.g.getFontGroupBySingleFontName(name); } pub inline fn getFontGroupByFamily(self: Self, family: graphics.FontFamily) FontGroupId { return self.common.g.getFontGroupByFamily(family); } pub inline fn getGraphics(self: Self) *graphics.Graphics { return self.common.g; } pub fn getDefaultFontGroup(self: Self) FontGroupId { return self.common.default_font_gid; } pub fn addInterval(self: *Self, node: *Node, dur: Duration, ctx: anytype, cb: IntervalHandler(@TypeOf(ctx))) IntervalId { const closure = Closure(@TypeOf(ctx), fn (IntervalEvent) void).init(self.alloc, ctx, cb).iface(); const s = IntervalSession.init(dur, node, closure); return self.common.interval_sessions.add(s) catch unreachable; } pub fn resetInterval(self: *Self, id: IntervalId) void { self.common.interval_sessions.getPtrNoCheck(id).progress_ms = 0; } pub fn removeInterval(self: *Self, id: IntervalId) void { self.common.interval_sessions.getNoCheck(id).deinit(self.alloc); self.common.interval_sessions.remove(id); } /// Receive mouse move events outside of the window. Useful for dragging operations. pub fn requestCaptureMouse(_: *Self, capture: bool) void { platform.captureMouse(capture); } pub fn requestFocus(self: *Self, node: *Node, on_blur: BlurHandler) void { if (self.common.focused_widget) |focused_widget| { if (focused_widget != node) { // Trigger blur for the current focused widget. self.common.focused_onblur(focused_widget, self); } } self.common.focused_widget = node; self.common.focused_onblur = on_blur; } pub fn isFocused(self: *Self, node: *Node) bool { if (self.common.focused_widget) |focused_widget| { return focused_widget == node; } else return false; } pub fn removeMouseMoveHandler(self: *Self, comptime Context: type, func: MouseMoveHandler(Context)) void { for (self.common.mouse_move_event_subs.items) |*sub, i| { if (sub.closure.user_fn == @ptrCast(*const anyopaque, func)) { sub.deinit(self.alloc); _ = self.common.mouse_move_event_subs.orderedRemove(i); break; } } if (self.common.mouse_move_event_subs.items.len == 0) { self.common.has_mouse_move_subs = false; } } pub fn addMouseUpHandler(self: *Self, node: *Node, ctx: anytype, cb: MouseUpHandler(@TypeOf(ctx))) void { const closure = Closure(@TypeOf(ctx), fn (MouseUpEvent) void).init(self.alloc, ctx, cb).iface(); const sub = GlobalSubscriber(platform.MouseUpEvent){ .sub = Subscriber(platform.MouseUpEvent){ .closure = closure, .node = node, }, .is_global = false, }; if (self.common.mouse_up_event_subs.getLast(node.mouse_up_list)) |last_id| { _ = self.common.mouse_up_event_subs.insertAfter(last_id, sub) catch unreachable; } else { node.mouse_up_list = self.common.mouse_up_event_subs.add(sub) catch unreachable; } } pub fn addGlobalMouseUpHandler(self: *Self, node: *Node, ctx: anytype, cb: MouseUpHandler(@TypeOf(ctx))) void { const closure = Closure(@TypeOf(ctx), fn (MouseUpEvent) void).init(self.alloc, ctx, cb).iface(); const sub = GlobalSubscriber(platform.MouseUpEvent){ .sub = Subscriber(platform.MouseUpEvent){ .closure = closure, .node = node, }, .is_global = true, }; var new_id: u32 = undefined; if (self.common.mouse_up_event_subs.getLast(node.mouse_up_list)) |last_id| { new_id = self.common.mouse_up_event_subs.insertAfter(last_id, sub) catch unreachable; } else { new_id = self.common.mouse_up_event_subs.add(sub) catch unreachable; node.mouse_up_list = new_id; } // Insert into global list. self.common.global_mouse_up_list.append(new_id) catch unreachable; } pub fn removeMouseUpHandler(self: *Self, node: *Node, comptime Context: type, func: MouseUpHandler(Context)) void { var cur = node.mouse_up_list; var prev = NullId; while (cur != NullId) { const sub = self.common.mouse_up_event_subs.getNoCheck(cur); if (sub.sub.closure.user_fn == @ptrCast(*const anyopaque, func)) { sub.sub.deinit(self.alloc); if (prev == NullId) { node.mouse_up_list = self.common.mouse_up_event_subs.getNextNoCheck(cur); self.common.mouse_up_event_subs.removeAssumeNoPrev(cur) catch unreachable; } else { self.common.mouse_up_event_subs.removeAfter(prev) catch unreachable; } if (sub.is_global) { for (self.common.global_mouse_up_list.items) |id, i| { if (id == cur) { _ = self.common.global_mouse_up_list.orderedRemove(i); break; } } } // Continue scanning for duplicates. } prev = cur; cur = self.common.mouse_up_event_subs.getNextNoCheck(cur); } } pub fn addMouseDownHandler(self: Self, node: *Node, ctx: anytype, cb: MouseDownHandler(@TypeOf(ctx))) void { const closure = Closure(@TypeOf(ctx), fn (MouseDownEvent) ui.EventResult).init(self.alloc, ctx, cb).iface(); const sub = SubscriberRet(platform.MouseDownEvent, ui.EventResult){ .closure = closure, .node = node, }; if (self.common.mouse_down_event_subs.getLast(node.mouse_down_list)) |last_id| { _ = self.common.mouse_down_event_subs.insertAfter(last_id, sub) catch unreachable; } else { node.mouse_down_list = self.common.mouse_down_event_subs.add(sub) catch unreachable; } } pub fn removeMouseDownHandler(self: *Self, node: *Node, comptime Context: type, func: MouseDownHandler(Context)) void { var cur = node.mouse_down_list; var prev = NullId; while (cur != NullId) { const sub = self.common.mouse_down_event_subs.getNoCheck(cur); if (sub.closure.user_fn == @ptrCast(*const anyopaque, func)) { sub.deinit(self.alloc); if (prev == NullId) { node.mouse_down_list = self.common.mouse_down_event_subs.getNextNoCheck(cur); self.common.mouse_down_event_subs.removeAssumeNoPrev(cur) catch unreachable; } else { self.common.mouse_down_event_subs.removeAfter(prev) catch unreachable; } // Continue scanning for duplicates. } prev = cur; cur = self.common.mouse_down_event_subs.getNextNoCheck(cur); } } pub fn addMouseScrollHandler(self: Self, node: *Node, ctx: anytype, cb: MouseScrollHandler(@TypeOf(ctx))) void { const closure = Closure(@TypeOf(ctx), fn (MouseScrollEvent) void).init(self.alloc, ctx, cb).iface(); const sub = Subscriber(platform.MouseScrollEvent){ .closure = closure, .node = node, }; if (self.common.mouse_scroll_event_subs.getLast(node.mouse_scroll_list)) |last_id| { _ = self.common.mouse_scroll_event_subs.insertAfter(last_id, sub) catch unreachable; } else { node.mouse_scroll_list = self.common.mouse_scroll_event_subs.add(sub) catch unreachable; } } pub fn removeMouseScrollHandler(self: *Self, node: *Node, comptime Context: type, func: MouseScrollHandler(Context)) void { var cur = node.mouse_scroll_list; var prev = NullId; while (cur != NullId) { const sub = self.common.mouse_scroll_event_subs.getNoCheck(cur); if (sub.closure.user_fn == @ptrCast(*const anyopaque, func)) { sub.deinit(self.alloc); if (prev == NullId) { node.mouse_scroll_list = self.common.mouse_scroll_event_subs.getNextNoCheck(cur); self.common.mouse_scroll_event_subs.removeAssumeNoPrev(cur) catch unreachable; } else { self.common.mouse_scroll_event_subs.removeAfter(prev) catch unreachable; } // Continue scanning for duplicates. } prev = cur; cur = self.common.mouse_scroll_event_subs.getNextNoCheck(cur); } } pub fn addMouseMoveHandler(self: *Self, node: *Node, ctx: anytype, cb: MouseMoveHandler(@TypeOf(ctx))) void { const closure = Closure(@TypeOf(ctx), fn (MouseMoveEvent) void).init(self.alloc, ctx, cb).iface(); const sub = Subscriber(platform.MouseMoveEvent){ .closure = closure, .node = node, }; self.common.mouse_move_event_subs.append(sub) catch unreachable; self.common.has_mouse_move_subs = true; } pub fn addKeyUpHandler(self: *Self, node: *Node, ctx: anytype, cb: KeyUpHandler(@TypeOf(ctx))) void { const closure = Closure(@TypeOf(ctx), fn (KeyUpEvent) void).init(self.alloc, ctx, cb).iface(); const sub = Subscriber(platform.KeyUpEvent){ .closure = closure, .node = node, }; if (self.common.key_up_event_subs.getLast(node.key_up_list)) |last_id| { _ = self.common.key_up_event_subs.insertAfter(last_id, sub) catch unreachable; } else { node.key_up_list = self.common.key_up_event_subs.add(sub) catch unreachable; } } /// Remove a handler from a node based on the function ptr. pub fn removeKeyUpHandler(self: *Self, node: *Node, func: *const anyopaque) void { var cur = node.key_up_list; var prev = NullId; while (cur != NullId) { const sub = self.common.key_up_event_subs.getNoCheck(cur); if (sub.closure.iface.getUserFunctionPtr() == func) { sub.deinit(); self.common.key_up_event_subs.removeAfter(prev); // Continue scanning for duplicates. } prev = cur; cur = self.common.key_up_event_subs.getNextNoCheck(cur) catch unreachable; } } pub fn addKeyDownHandler(self: *Self, node: *Node, ctx: anytype, cb: KeyDownHandler(@TypeOf(ctx))) void { const closure = Closure(@TypeOf(ctx), fn (KeyDownEvent) void).init(self.alloc, ctx, cb).iface(); const sub = Subscriber(platform.KeyDownEvent){ .closure = closure, .node = node, }; if (self.common.key_down_event_subs.getLast(node.key_down_list)) |last_id| { _ = self.common.key_down_event_subs.insertAfter(last_id, sub) catch unreachable; } else { node.key_down_list = self.common.key_down_event_subs.add(sub) catch unreachable; } } pub fn removeKeyDownHandler(self: *Self, node: *Node, comptime Context: type, func: KeyDownHandler(Context)) void { var cur = node.key_down_list; var prev = NullId; while (cur != NullId) { const sub = self.common.key_down_event_subs.getNoCheck(cur); if (sub.closure.iface.getUserFunctionPtr() == @ptrCast(*const anyopaque, func)) { sub.deinit(); self.common.key_down_event_subs.removeAfter(prev); // Continue scanning for duplicates. } prev = cur; cur = self.common.key_down_event_subs.getNextNoCheck(cur) catch unreachable; } } pub fn nextPostLayout(self: *Self, ctx: anytype, cb: fn(@TypeOf(ctx)) void) void { return self.common.nextPostLayout(ctx, cb); } }; // TODO: Refactor similar ops to their own struct. pub const ModuleCommon = struct { const Self = @This(); alloc: std.mem.Allocator, mod: *Module, /// Arena allocator that gets freed after each update cycle. arena_allocator: std.heap.ArenaAllocator, arena_alloc: std.mem.Allocator, g: *Graphics, text_measures: ds.CompactUnorderedList(TextMeasureId, TextMeasure), interval_sessions: ds.CompactUnorderedList(u32, IntervalSession), // TODO: Use one buffer for all the handlers. /// Keyboard handlers. key_up_event_subs: ds.CompactSinglyLinkedListBuffer(u32, Subscriber(platform.KeyUpEvent)), key_down_event_subs: ds.CompactSinglyLinkedListBuffer(u32, Subscriber(platform.KeyDownEvent)), /// Mouse handlers. mouse_up_event_subs: ds.CompactSinglyLinkedListBuffer(u32, GlobalSubscriber(platform.MouseUpEvent)), global_mouse_up_list: std.ArrayList(u32), mouse_down_event_subs: ds.CompactSinglyLinkedListBuffer(u32, SubscriberRet(platform.MouseDownEvent, ui.EventResult)), mouse_scroll_event_subs: ds.CompactSinglyLinkedListBuffer(u32, Subscriber(platform.MouseScrollEvent)), /// Mouse move events fire far more frequently so it's better to just iterate a list and skip hit test. /// TODO: Implement a compact tree of nodes for mouse events. mouse_move_event_subs: std.ArrayList(Subscriber(platform.MouseMoveEvent)), has_mouse_move_subs: bool, /// Currently focused widget. focused_widget: ?*Node, focused_onblur: BlurHandler, /// Scratch vars to track the last focused widget. last_focused_widget: ?*Node, hit_last_focused: bool, widget_hit_flag: bool, next_post_layout_cbs: std.ArrayList(ClosureIface(fn () void)), // next_post_render_cbs: std.ArrayList(*Node), // TODO: design themes. default_font_gid: FontGroupId, /// Keys are assumed to be static memory so they don't need to be freed. id_map: std.AutoHashMap(ui.WidgetUserId, *Node), ctx: CommonContext, context_provider: fn (key: u32) ?*anyopaque, fn init(self: *Self, alloc: std.mem.Allocator, mod: *Module, g: *Graphics) void { const S = struct { fn defaultContextProvider(key: u32) ?*anyopaque { _ = key; return null; } }; self.* = .{ .alloc = alloc, .mod = mod, .arena_allocator = std.heap.ArenaAllocator.init(alloc), .arena_alloc = undefined, .g = g, .text_measures = ds.CompactUnorderedList(TextMeasureId, TextMeasure).init(alloc), // .default_font_gid = g.getFontGroupBySingleFontName("Nunito Sans"), .default_font_gid = g.getDefaultFontGroupId(), .interval_sessions = ds.CompactUnorderedList(u32, IntervalSession).init(alloc), .key_up_event_subs = ds.CompactSinglyLinkedListBuffer(u32, Subscriber(platform.KeyUpEvent)).init(alloc), .key_down_event_subs = ds.CompactSinglyLinkedListBuffer(u32, Subscriber(platform.KeyDownEvent)).init(alloc), .mouse_up_event_subs = ds.CompactSinglyLinkedListBuffer(u32, GlobalSubscriber(platform.MouseUpEvent)).init(alloc), .global_mouse_up_list = std.ArrayList(u32).init(alloc), .mouse_down_event_subs = ds.CompactSinglyLinkedListBuffer(u32, SubscriberRet(platform.MouseDownEvent, ui.EventResult)).init(alloc), .mouse_move_event_subs = std.ArrayList(Subscriber(platform.MouseMoveEvent)).init(alloc), .mouse_scroll_event_subs = ds.CompactSinglyLinkedListBuffer(u32, Subscriber(platform.MouseScrollEvent)).init(alloc), .has_mouse_move_subs = false, .next_post_layout_cbs = std.ArrayList(ClosureIface(fn () void)).init(alloc), // .next_post_render_cbs = std.ArrayList(*Node).init(alloc), .focused_widget = null, .focused_onblur = undefined, .last_focused_widget = null, .hit_last_focused = false, .widget_hit_flag = false, .ctx = .{ .common = self, .alloc = alloc, }, .context_provider = S.defaultContextProvider, .id_map = std.AutoHashMap(ui.WidgetUserId, *Node).init(alloc), }; self.arena_alloc = self.arena_allocator.allocator(); } fn deinit(self: *Self) void { self.id_map.deinit(); self.text_measures.deinit(); self.next_post_layout_cbs.deinit(); // self.next_post_render_cbs.deinit(); { var iter = self.interval_sessions.iterator(); while (iter.next()) |it| { it.deinit(self.alloc); } self.interval_sessions.deinit(); } { var iter = self.key_up_event_subs.iterator(); while (iter.next()) |it| { it.data.deinit(self.alloc); } self.key_up_event_subs.deinit(); } { var iter = self.key_down_event_subs.iterator(); while (iter.next()) |it| { it.data.deinit(self.alloc); } self.key_down_event_subs.deinit(); } { var iter = self.mouse_up_event_subs.iterator(); while (iter.next()) |it| { it.data.sub.deinit(self.alloc); } self.mouse_up_event_subs.deinit(); } self.global_mouse_up_list.deinit(); { var iter = self.mouse_down_event_subs.iterator(); while (iter.next()) |it| { it.data.deinit(self.alloc); } self.mouse_down_event_subs.deinit(); } { var iter = self.mouse_scroll_event_subs.iterator(); while (iter.next()) |it| { it.data.deinit(self.alloc); } self.mouse_scroll_event_subs.deinit(); } for (self.mouse_move_event_subs.items) |*it| { it.deinit(self.alloc); } self.mouse_move_event_subs.deinit(); self.arena_allocator.deinit(); } fn createTextMeasure(self: *Self, font_gid: FontGroupId, font_size: f32) TextMeasureId { return self.text_measures.add(TextMeasure.init(&.{}, font_gid, font_size)) catch unreachable; } fn getTextMeasure(self: *Self, id: TextMeasureId) *TextMeasure { return self.text_measures.getPtrNoCheck(id); } pub fn destroyTextMeasure(self: *Self, id: TextMeasureId) void { self.text_measures.remove(id); } fn updateIntervals(self: *Self, delta_ms: f32, event_ctx: *EventContext) void { var iter = self.interval_sessions.iterator(); while (iter.nextPtr()) |it| { it.progress_ms += delta_ms; if (it.progress_ms > @intToFloat(f32, it.dur.toMillis())) { it.call(event_ctx); it.progress_ms = 0; } } } fn nextPostLayout(self: *Self, ctx: anytype, cb: fn (@TypeOf(ctx)) void) void { const closure = Closure(@TypeOf(ctx), fn () void).init(self.alloc, ctx, cb).iface(); self.next_post_layout_cbs.append(closure) catch unreachable; } /// Given id as an enum literal tag, return the node. pub fn getNodeByTag(self: Self, comptime lit: @Type(.EnumLiteral)) ?*Node { const id = stdx.meta.enumLiteralId(lit); return self.id_map.get(id); } }; pub const ModuleContext = struct { const Self = @This(); mod: *Module, fn init(mod: *Module) Self { return .{ .mod = mod, }; } }; pub const InitContext = struct { mod: *Module, alloc: std.mem.Allocator, common: *CommonContext, node: *Node, const Self = @This(); fn init(mod: *Module) Self { return .{ .mod = mod, .alloc = mod.alloc, .common = &mod.common.ctx, .node = undefined, }; } fn prepareForNode(self: *Self, node: *Node) void { self.node = node; } pub fn getModuleContext(self: *Self) *ModuleContext { return &self.mod.mod_ctx; } // TODO: findChildrenByTag // TODO: findChildByKey pub fn findChildWidgetByType(self: *Self, comptime Widget: type) ?WidgetRef(Widget) { const needle = getWidgetIdByType(Widget); const walker = stdx.algo.recursive.ChildArrayListSearchWalker(*Node); const S = struct { fn pred(type_id: WidgetTypeId, node: *Node) bool { return @ptrToInt(node.vtable) == type_id; } }; const res = stdx.algo.recursive.searchPreMany(WidgetTypeId, needle, *Node, self.node.children.items, walker, S.pred); if (res != null) { return WidgetRef(Widget).init(res.?); } else { return null; } } pub usingnamespace MixinContextInputOps(Self); pub usingnamespace MixinContextEventOps(Self); pub usingnamespace MixinContextNodeOps(Self); pub usingnamespace MixinContextFontOps(Self); pub usingnamespace MixinContextSharedOps(Self); }; /// Contains an extra global flag. fn GlobalSubscriber(comptime T: type) type { return struct { sub: Subscriber(T), is_global: bool, }; } fn SubscriberRet(comptime T: type, comptime Return: type) type { return struct { const Self = @This(); closure: ClosureIface(fn (Event(T)) Return), node: *Node, fn handleEvent(self: Self, ctx: *EventContext, e: T) Return { ctx.node = self.node; return self.closure.call(.{ Event(T){ .ctx = ctx, .val = e, }, }); } fn deinit(self: Self, alloc: std.mem.Allocator) void { self.closure.deinit(alloc); } }; } fn Subscriber(comptime T: type) type { return struct { const Self = @This(); closure: ClosureIface(fn (Event(T)) void), node: *Node, fn handleEvent(self: Self, ctx: *EventContext, e: T) void { ctx.node = self.node; self.closure.call(.{ Event(T){ .ctx = ctx, .val = e, }, }); } fn deinit(self: Self, alloc: std.mem.Allocator) void { self.closure.deinit(alloc); } }; } pub const BuildContext = struct { alloc: std.mem.Allocator, arena_alloc: std.mem.Allocator, mod: *Module, // Temporary buffers used to build Frames in Widget's `build` function. // Cleared on the next update cycle. FrameIds generated are indexes to this buffer. frames: std.ArrayList(Frame), // One ArrayList is used to store multiple frame lists. // Appends a complete list and returns the start index and size as the key. frame_lists: std.ArrayList(FrameId), // Stores variable sized Widget props data. Appends props data and returns // the start index and size as the key. frame_props: ds.DynamicArrayList(u32, u8), u8_buf: std.ArrayList(u8), // Current node. node: *Node, // Current Frame used. Must use id since pointer could be invalidated. frame_id: FrameId, const Self = @This(); fn init(alloc: std.mem.Allocator, arena_alloc: std.mem.Allocator, mod: *Module) Self { return .{ .alloc = alloc, .arena_alloc = arena_alloc, .mod = mod, .frames = std.ArrayList(Frame).init(alloc), .frame_lists = std.ArrayList(FrameId).init(alloc), .frame_props = ds.DynamicArrayList(u32, u8).init(alloc), .u8_buf = std.ArrayList(u8).init(alloc), .node = undefined, .frame_id = undefined, }; } fn deinit(self: *Self) void { self.frames.deinit(); self.frame_lists.deinit(); self.frame_props.deinit(); self.u8_buf.deinit(); } /// Creates a closure in arena buffer, and returns an iface. pub fn closure(self: *Self, ctx: anytype, user_fn: anytype) Function(stdx.meta.FnAfterFirstParam(@TypeOf(user_fn))) { const Params = comptime stdx.meta.FnParams(@TypeOf(user_fn)); if (Params.len == 0) { @compileError("Expected first param to be: " ++ @typeName(@TypeOf(ctx))); } const InnerFn = stdx.meta.FnAfterFirstParam(@TypeOf(user_fn)); const c = Closure(@TypeOf(ctx), InnerFn).init(self.mod.common.arena_alloc, ctx, user_fn).iface(); return Function(InnerFn).initClosureIface(c); } /// Returns a wrapper over a free function. pub fn func(self: *Self, comptime user_fn: anytype) Function(@TypeOf(user_fn)) { _ = self; const Fn = @TypeOf(user_fn); stdx.meta.assertFunctionType(Fn); return Function(Fn).init(user_fn); } /// Returns a wrapper over a free function with a context pointer. This doesn't need any allocations. pub fn funcExt(self: *Self, ctx_ptr: anytype, comptime user_fn: anytype) Function(stdx.meta.FnAfterFirstParam(@TypeOf(user_fn))) { _ = self; const Params = comptime stdx.meta.FnParams(@TypeOf(user_fn)); if (Params[0].arg_type.? != @TypeOf(ctx_ptr)) { @compileError("Expected first param to be: " ++ @typeName(@TypeOf(ctx_ptr))); } const InnerFn = stdx.meta.FnAfterFirstParam(@TypeOf(user_fn)); return Function(InnerFn).initContext(ctx_ptr, user_fn); } pub fn range(self: *Self, count: usize, ctx: anytype, build_fn: fn (@TypeOf(ctx), *BuildContext, u32) FrameId) FrameListPtr { const start_idx = self.frame_lists.items.len; var i: u32 = 0; var buf_i: u32 = 0; // Preallocate the list so that the frame ids can be layed out contiguously. Otherwise, the frame_lists array runs the risk of being modified by the user build fn. // TODO: This is inefficient if the range is mostly a filter, leaving empty frame slots. One way to solve this is to use a separate stack buffer. self.frame_lists.resize(self.frame_lists.items.len + count) catch unreachable; while (i < count) : (i += 1) { const frame_id = build_fn(ctx, self, @intCast(u32, i)); if (frame_id != NullFrameId) { self.frame_lists.items[start_idx + buf_i] = frame_id; buf_i += 1; } } return FrameListPtr.init(@intCast(u32, start_idx), buf_i); } fn resetBuffer(self: *Self) void { self.frames.clearRetainingCapacity(); self.frame_lists.clearRetainingCapacity(); self.frame_props.clearRetainingCapacity(); self.u8_buf.clearRetainingCapacity(); } fn prepareCall(self: *Self, frame_id: FrameId, node: *Node) void { self.frame_id = frame_id; self.node = node; } /// Appends formatted string to temporary buffer. pub fn fmt(self: *Self, comptime format: []const u8, args: anytype) []const u8 { const start = self.u8_buf.items.len; std.fmt.format(self.u8_buf.writer(), format, args) catch unreachable; return self.u8_buf.items[start..]; } /// Short-hand for createFrame. pub inline fn decl(self: *Self, comptime Widget: type, props: anytype) FrameId { return self.createFrame(Widget, props); } pub inline fn list(self: *Self, tuple_or_slice: anytype) FrameListPtr { const IsTuple = comptime std.meta.trait.isTuple(@TypeOf(tuple_or_slice)); if (IsTuple) { // createFrameList doesn't support tuples right now because of tuples nested in anonymous struct is bugged, // so we convert it to an array. const arr: [stdx.meta.TupleLen(@TypeOf(tuple_or_slice))]FrameId = tuple_or_slice; return self.createFrameList(arr); } else { return self.createFrameList(tuple_or_slice); } } pub inline fn fragment(self: *Self, list_: FrameListPtr) FrameId { const frame = Frame.init(FragmentVTable, null, null, FramePropsPtr.init(0, 0), list_); const frame_id = @intCast(FrameId, @intCast(u32, self.frames.items.len)); self.frames.append(frame) catch unreachable; return frame_id; } /// Allows caller to bind a FrameId to a NodeRef. One frame can be binded to many NodeRefs. pub fn bindFrame(self: *Self, frame_id: FrameId, ref: *ui.NodeRef) void { if (frame_id != NullFrameId) { const frame = &self.frames.items[frame_id]; const node = self.arena_alloc.create(BindNode) catch fatal(); node.node_ref = ref; node.next = frame.node_binds; frame.node_binds = node; } } fn createFrameList(self: *Self, frame_ids: anytype) FrameListPtr { const Type = @TypeOf(frame_ids); const IsSlice = comptime std.meta.trait.isSlice(Type) and @typeInfo(Type).Pointer.child == FrameId; const IsArray = @typeInfo(Type) == .Array; // const IsTuple = comptime std.meta.trait.isTuple(Type); comptime { // Currently disallow tuples due to https://github.com/ziglang/zig/issues/6043. if (!IsSlice and !IsArray) { @compileError("unsupported " ++ @typeName(Type)); } } const start_idx = @intCast(u32, self.frame_lists.items.len); self.frame_lists.ensureUnusedCapacity(frame_ids.len) catch @panic("error"); if (IsSlice or IsArray) { for (frame_ids) |id| { if (id != NullFrameId) { self.frame_lists.appendAssumeCapacity(id); } } } else { stdx.debug.panic("unexpected"); // inline for (std.meta.fields(Type)) |f| { // const frame_id = @field(frame_ids, f.name); // log.warn("appending {} {s} {}", .{frame_id, f.name, frame_ids}); // self.frame_lists.append(frame_id) catch unreachable; // } } return FrameListPtr.init(start_idx, @intCast(u32, self.frame_lists.items.len) - start_idx); } fn getFrame(self: Self, id: FrameId) Frame { return self.frames.items[id]; } fn getFrameList(self: *Self, ptr: FrameListPtr) []const FrameId { const end_idx = ptr.id + ptr.len; return self.frame_lists.items[ptr.id..end_idx]; } fn createFrame(self: *Self, comptime Widget: type, build_props: anytype) FrameId { // log.warn("createFrame {}", .{build_props}); const BuildProps = @TypeOf(build_props); if (@hasField(BuildProps, "bind")) { if (stdx.meta.FieldType(BuildProps, .bind) != *WidgetRef(Widget)) { @compileError("Expected bind type to be: " ++ @typeName(*WidgetRef(Widget))); } } if (@hasField(BuildProps, "id")) { if (@typeInfo(stdx.meta.FieldType(BuildProps, .id)) != .EnumLiteral) { @compileError("Expected id type to be an enum literal."); } } const bind: ?*anyopaque = if (@hasField(BuildProps, "bind")) build_props.bind else null; const id = if (@hasField(BuildProps, "id")) stdx.meta.enumLiteralId(build_props.id) else null; const props_ptr = b: { const HasProps = comptime WidgetHasProps(Widget); // First use comptime to get a list of valid fields to be copied to props. const ValidFields = comptime b2: { var res: []const std.builtin.TypeInfo.StructField = &.{}; for (std.meta.fields(BuildProps)) |f| { // Skip special fields. if (string.eq("id", f.name)) { continue; } else if (string.eq("bind", f.name)) { continue; } else if (!HasProps) { @compileError("No Props type declared in " ++ @typeName(Widget) ++ " for " ++ f.name); } else if (@hasField(WidgetProps(Widget), f.name)) { res = res ++ &[_]std.builtin.TypeInfo.StructField{f}; } else { @compileError(f.name ++ " isn't declared in " ++ @typeName(Widget) ++ ".Props"); } } break :b2 res; }; _ = ValidFields; if (HasProps) { var props: WidgetProps(Widget) = undefined; inline for (std.meta.fields(WidgetProps(Widget))) |Field| { if (@hasField(BuildProps, Field.name)) { @field(props, Field.name) = @field(build_props, Field.name); } else { if (Field.default_value) |def| { // Set default value. @field(props, Field.name) = @ptrCast(*const Field.field_type, def).*; } else { @compileError("Required field " ++ Field.name ++ " in " ++ @typeName(Widget)); } } } // Then inline the copy statements. // inline for (ValidFields) |f| { // @field(props, f.name) = @field(build_props, f.name); // } // log.warn("set frame props", .{}); break :b self.frame_props.append(props) catch unreachable; } else { break :b FramePropsPtr.init(0, 0); } }; const vtable = GenWidgetVTable(Widget); const frame = Frame.init(vtable, id, bind, props_ptr, FrameListPtr.init(0, 0)); const frame_id = @intCast(FrameId, @intCast(u32, self.frames.items.len)); self.frames.append(frame) catch unreachable; // log.warn("created frame {}", .{frame_id}); return frame_id; } }; const TestModule = struct { g: graphics.Graphics, mod: ui.Module, size: ui.LayoutSize, const Self = @This(); pub fn init(self: *Self) void { self.g.init(t.alloc, 1); self.mod.init(t.alloc, &self.g); self.size = LayoutSize.init(800, 600); } pub fn deinit(self: *Self) void { self.mod.deinit(); self.g.deinit(); } pub fn preUpdate(self: *Self, ctx: anytype, comptime bootstrap_fn: fn (@TypeOf(ctx), *BuildContext) FrameId) !void { try self.mod.preUpdate(0, ctx, bootstrap_fn, self.size); } pub fn getRoot(self: Self) ?*Node { return self.mod.root_node; } pub fn getNodeByTag(self: Self, comptime lit: @Type(.EnumLiteral)) ?*Node { return self.mod.common.getNodeByTag(lit); } }; test "Node removal also removes the children." { const A = struct { props: struct { child: FrameId, }, fn build(self: *@This(), _: *BuildContext) FrameId { return self.props.child; } }; const B = struct {}; const S = struct { fn bootstrap(delete: bool, c: *BuildContext) FrameId { var child: FrameId = NullFrameId; if (!delete) { child = c.decl(A, .{ .child = c.decl(B, .{}), }); } return c.decl(A, .{ .id = .root, .child = child, }); } }; var mod: TestModule = undefined; mod.init(); defer mod.deinit(); try mod.preUpdate(false, S.bootstrap); const root = mod.getNodeByTag(.root).?; try t.eq(root.numChildrenR(), 2); try mod.preUpdate(true, S.bootstrap); try t.eq(root.numChildrenR(), 0); } test "User root should not allow fragment frame." { const A = struct { }; const S = struct { fn bootstrap(_: void, c: *BuildContext) FrameId { const list = c.list(.{ c.decl(A, .{}), c.decl(A, .{}), }); return c.fragment(list); } }; var mod: TestModule = undefined; mod.init(); defer mod.deinit(); try t.expectError(mod.preUpdate({}, S.bootstrap), error.UserRootCantBeFragment); } test "BuildContext.list() will skip over a NullFrameId item." { const B = struct {}; const A = struct { fn build(_: *@This(), c: *BuildContext) FrameId { return c.fragment(c.list(.{ NullFrameId, c.decl(B, .{}), })); } }; const S = struct { fn bootstrap(_: void, c: *BuildContext) FrameId { return c.decl(A, .{ .id = .root, }); } }; var mod: TestModule = undefined; mod.init(); defer mod.deinit(); try mod.preUpdate({}, S.bootstrap); const root = mod.getNodeByTag(.root); try t.eq(root.?.vtable, GenWidgetVTable(A)); try t.eq(root.?.children.items.len, 1); try t.eq(root.?.children.items[0].vtable, GenWidgetVTable(B)); } test "Don't allow nested fragment frames." { const A = struct { props: struct { child: FrameId }, fn build(self: *@This(), _: *BuildContext) FrameId { return self.props.child; } }; const B = struct {}; const S = struct { fn bootstrap(_: void, c: *ui.BuildContext) FrameId { const nested_list = c.list(.{ c.decl(B, .{}), }); const list = c.list(.{ c.decl(B, .{}), c.fragment(nested_list), }); return c.decl(A, .{ .child = c.fragment(list), }); } }; var mod: TestModule = undefined; mod.init(); defer mod.deinit(); try t.expectError(mod.preUpdate({}, S.bootstrap), error.NestedFragment); } test "BuildContext.range" { const A = struct { props: struct { children: ui.FrameListPtr, }, fn build(self: *@This(), c: *BuildContext) FrameId { return c.fragment(self.props.children); } }; const B = struct {}; // Test case where a child widget uses BuildContext.list. Check if this causes problems with BuildContext.range. const S = struct { fn bootstrap(_: void, c: *BuildContext) FrameId { return c.decl(A, .{ .id = .root, .children = c.range(1, {}, buildChild), }); } fn buildChild(_: void, c: *BuildContext, _: u32) FrameId { const list = c.list(.{ c.decl(B, .{}), }); return c.decl(A, .{ .children = list }); } }; var mod: TestModule = undefined; mod.init(); defer mod.deinit(); try mod.preUpdate({}, S.bootstrap); const root = mod.getNodeByTag(.root); try t.eq(root.?.vtable, GenWidgetVTable(A)); try t.eq(root.?.children.items[0].vtable, GenWidgetVTable(A)); try t.eq(root.?.children.items[0].children.items[0].vtable, GenWidgetVTable(B)); } test "Widget instance lifecycle." { const A = struct { pub fn init(_: *@This(), c: *InitContext) void { c.addKeyUpHandler({}, onKeyUp); c.addKeyDownHandler({}, onKeyDown); c.addMouseDownHandler({}, onMouseDown); c.addMouseUpHandler({}, onMouseUp); c.addMouseMoveHandler(@as(u32, 1), onMouseMove); _ = c.addInterval(Duration.initSecsF(1), {}, onInterval); c.requestFocus(onBlur); } fn onInterval(_: void, _: ui.IntervalEvent) void {} fn onBlur(_: *ui.Node, _: *ui.CommonContext) void {} fn onKeyUp(_: void, _: KeyUpEvent) void {} fn onKeyDown(_: void, _: KeyDownEvent) void {} fn onMouseDown(_: void, _: MouseDownEvent) ui.EventResult { return .Continue; } fn onMouseUp(_: void, _: MouseUpEvent) void {} fn onMouseMove(_: u32, _: MouseMoveEvent) void {} }; const S = struct { fn bootstrap(decl: bool, c: *BuildContext) FrameId { if (decl) { return c.decl(A, .{ .id = .root, }); } else { return NullFrameId; } } }; var tmod: TestModule = undefined; tmod.init(); defer tmod.deinit(); const mod = &tmod.mod; try tmod.preUpdate(true, S.bootstrap); // Widget instance should exist with event handlers. var root = tmod.getNodeByTag(.root); try t.eq(root.?.vtable, GenWidgetVTable(A)); try t.eq(mod.common.focused_widget.?, root.?); try t.eq(mod.common.key_up_event_subs.size(), 1); const keyup_sub = mod.common.key_up_event_subs.iterFirstValueNoCheck(); try t.eq(keyup_sub.node, root.?); try t.eq(keyup_sub.closure.user_fn, A.onKeyUp); try t.eq(mod.common.key_down_event_subs.size(), 1); const keydown_sub = mod.common.key_down_event_subs.iterFirstValueNoCheck(); try t.eq(keydown_sub.node, root.?); try t.eq(keydown_sub.closure.user_fn, A.onKeyDown); try t.eq(mod.common.mouse_down_event_subs.size(), 1); const mousedown_sub = mod.common.mouse_down_event_subs.iterFirstValueNoCheck(); try t.eq(mousedown_sub.node, root.?); try t.eq(mousedown_sub.closure.user_fn, A.onMouseDown); try t.eq(mod.common.mouse_up_event_subs.size(), 1); const mouseup_sub = mod.common.mouse_up_event_subs.iterFirstValueNoCheck(); try t.eq(mouseup_sub.is_global, false); try t.eq(mouseup_sub.sub.node, root.?); try t.eq(mouseup_sub.sub.closure.user_fn, A.onMouseUp); try t.eq(mod.common.mouse_move_event_subs.items.len, 1); const mousemove_sub = mod.common.mouse_move_event_subs.items[0]; try t.eq(mousemove_sub.node, root.?); try t.eq(mousemove_sub.closure.user_fn, A.onMouseMove); try t.eq(mod.common.interval_sessions.size(), 1); var iter = mod.common.interval_sessions.iterator(); const interval_sub = iter.next().?; try t.eq(interval_sub.node, root.?); try t.eq(interval_sub.closure.user_fn, A.onInterval); try tmod.preUpdate(false, S.bootstrap); // Widget instance should be removed and handlers should have been cleaned up. root = tmod.getNodeByTag(.root); try t.eq(root, null); try t.eq(mod.common.focused_widget, null); try t.eq(mod.common.key_up_event_subs.size(), 0); try t.eq(mod.common.key_down_event_subs.size(), 0); try t.eq(mod.common.mouse_down_event_subs.size(), 0); try t.eq(mod.common.mouse_up_event_subs.size(), 0); try t.eq(mod.common.mouse_move_event_subs.items.len, 0); try t.eq(mod.common.interval_sessions.size(), 0); } test "Module.update creates or updates existing node" { var g: graphics.Graphics = undefined; g.init(t.alloc, 1); defer g.deinit(); const Foo = struct { }; const Bar = struct { }; const Root = struct { flag: bool, pub fn init(self: *@This(), _: *InitContext) void { self.* = .{ .flag = true, }; } fn build(self: *@This(), c: *BuildContext) FrameId { if (self.flag) { return c.decl(Foo, .{}); } else { return c.decl(Bar, .{}); } } }; { // Different root frame type creates new node. const S2 = struct { fn bootstrap(flag: bool, c: *BuildContext) FrameId { if (flag) { return c.decl(Foo, .{ .id = .root, }); } else { return c.decl(Bar, .{ .id = .root, }); } } }; var mod: TestModule = undefined; mod.init(); defer mod.deinit(); try mod.preUpdate(true, S2.bootstrap); var root = mod.getNodeByTag(.root); try t.eq(root.?.vtable, GenWidgetVTable(Foo)); try mod.preUpdate(false, S2.bootstrap); root = mod.getNodeByTag(.root); try t.eq(root.?.vtable, GenWidgetVTable(Bar)); } { // Different child frame type creates new node. const S2 = struct { fn bootstrap(_: void, c: *BuildContext) FrameId { return c.decl(Root, .{ .id = .root, }); } }; var tmod: TestModule = undefined; tmod.init(); defer tmod.deinit(); try tmod.preUpdate({}, S2.bootstrap); var root = tmod.getNodeByTag(.root); try t.eq(root.?.numChildren(), 1); try t.eq(root.?.getChild(0).vtable, GenWidgetVTable(Foo)); root.?.getWidget(Root).flag = false; try tmod.preUpdate({}, S2.bootstrap); root = tmod.getNodeByTag(.root); try t.eq(root.?.numChildren(), 1); try t.eq(root.?.getChild(0).vtable, GenWidgetVTable(Bar)); } } // test "BuildContext.new disallows using a prop that's not declared in Component.Props" { // const Foo = struct { // const Props = struct { // bar: usize, // }; // }; // var mod: Module = undefined; // Module.init(&mod, t.alloc, &g, LayoutSize.init(800, 600), undefined); // defer mod.deinit(); // _ = mod.build_ctx.new(.Foo, .{ .text = "foo" }); // } pub const LayoutConstraints = struct { min_width: f32, max_width: f32, min_height: f32, max_height: f32, }; pub const Layout = struct { x: f32, y: f32, width: f32, height: f32, const Self = @This(); pub fn init(x: f32, y: f32, width: f32, height: f32) Self { return .{ .x = x, .y = y, .width = width, .height = height, }; } pub fn initWithSize(x: f32, y: f32, size: LayoutSize) Self { return .{ .x = x, .y = y, .width = size.width, .height = size.height, }; } pub fn contains(self: Self, x: f32, y: f32) bool { return x >= self.x and x <= self.x + self.width and y >= self.y and y <= self.y + self.height; } }; const IntervalSession = struct { const Self = @This(); dur: Duration, progress_ms: f32, node: *Node, closure: ClosureIface(fn (IntervalEvent) void), fn init(dur: Duration, node: *Node, closure: ClosureIface(fn (IntervalEvent) void)) Self { return .{ .dur = dur, .progress_ms = 0, .node = node, .closure = closure, }; } fn deinit(self: Self, alloc: std.mem.Allocator) void { self.closure.deinit(alloc); } fn call(self: *Self, ctx: *EventContext) void { ctx.node = self.node; self.closure.call(.{ IntervalEvent{ .progress_ms = self.progress_ms, .ctx = ctx, }, }); } }; pub const IntervalEvent = struct { progress_ms: f32, ctx: *EventContext, }; fn WidgetHasProps(comptime Widget: type) bool { if (!@hasField(Widget, "props")) { return false; } const PropsField = std.meta.fieldInfo(Widget, .props); return @typeInfo(PropsField.field_type) == .Struct; } fn WidgetProps(comptime Widget: type) type { if (WidgetHasProps(Widget)) { return std.meta.fieldInfo(Widget, .props).field_type; } else { @compileError(@typeName(Widget) ++ " doesn't have props field."); } } const UpdateError = error { NestedFragment, UserRootCantBeFragment, };
ui/src/module.zig
const std = @import("std"); const Type = @import("types.zig").Type; const Status = @import("status.zig").Status; const Memory = @import("memory.zig").Memory; const testing = std.testing; const allocator = std.heap.page_allocator; pub const CPU = struct { const INITIAL_ADDRESS = 0xF000; const STACK_BASE = 0x0100; PC: Type.Word, // Program Counter PS: Status, // Processor Status regs: [4]Type.Byte, memory: Memory, // Memory bank with 64 KB -- wow ticks: u32, // Cycle counter // TODO: I would like these to be members of an enum, and have an array of // them. const A = 0; const X = 1; const Y = 2; const SP = 3; const DisplaceOp = enum { ShiftLeft, ShiftRight, RotateLeft, RotateRight, }; const NumOp = enum { Add, Subtract, }; const BitOp = enum { And, InclusiveOr, ExclusiveOr, Bit, }; const IncDecOp = enum { Increment, Decrement, }; const ClearSet = enum { Clear, Set, }; const AddressingMode = enum { Immediate, ZeroPage, ZeroPageX, ZeroPageY, Absolute, AbsoluteX, AbsoluteY, Indirect, IndirectX, IndirectY, }; const OP = enum(Type.Byte) { LDA_IMM = 0xA9, LDA_ZP = 0xA5, LDA_ZPX = 0xB5, LDA_ABS = 0xAD, LDA_ABSX = 0xBD, LDA_ABSY = 0xB9, LDA_INDX = 0xA1, LDA_INDY = 0xB1, LDX_IMM = 0xA2, LDX_ZP = 0xA6, LDX_ZPY = 0xB6, LDX_ABS = 0xAE, LDX_ABSY = 0xBE, LDY_IMM = 0xA0, LDY_ZP = 0xA4, LDY_ZPX = 0xB4, LDY_ABS = 0xAC, LDY_ABSX = 0xBC, STA_ZP = 0x85, STA_ZPX = 0x95, STA_ABS = 0x8D, STA_ABSX = 0x9D, STA_ABSY = 0x99, STA_INDX = 0x81, STA_INDY = 0x91, STX_ZP = 0x86, STX_ZPY = 0x96, STX_ABS = 0x8E, STY_ZP = 0x84, STY_ZPX = 0x94, STY_ABS = 0x8C, TAX = 0xAA, TAY = 0xA8, TXA = 0x8A, TYA = 0x98, TSX = 0xBA, TXS = 0x9A, PHA = 0x48, PHP = 0x08, PLA = 0x68, PLP = 0x28, AND_IMM = 0x29, AND_ZP = 0x25, AND_ZPX = 0x35, AND_ABS = 0x2D, AND_ABSX = 0x3D, AND_ABSY = 0x39, AND_INDX = 0x21, AND_INDY = 0x31, EOR_IMM = 0x49, EOR_ZP = 0x45, EOR_ZPX = 0x55, EOR_ABS = 0x4D, EOR_ABSX = 0x5D, EOR_ABSY = 0x59, EOR_INDX = 0x41, EOR_INDY = 0x51, ORA_IMM = 0x09, ORA_ZP = 0x05, ORA_ZPX = 0x15, ORA_ABS = 0x0D, ORA_ABSX = 0x1D, ORA_ABSY = 0x19, ORA_INDX = 0x01, ORA_INDY = 0x11, BIT_ZP = 0x24, BIT_ABS = 0x2C, ADC_IMM = 0x69, ADC_ZP = 0x65, ADC_ZPX = 0x75, ADC_ABS = 0x6D, ADC_ABSX = 0x7D, ADC_ABSY = 0x79, ADC_INDX = 0x61, ADC_INDY = 0x71, SBC_IMM = 0xE9, SBC_ZP = 0xE5, SBC_ZPX = 0xF5, SBC_ABS = 0xED, SBC_ABSX = 0xFD, SBC_ABSY = 0xF9, SBC_INDX = 0xE1, SBC_INDY = 0xF1, CMP_IMM = 0xC9, CMP_ZP = 0xC5, CMP_ZPX = 0xD5, CMP_ABS = 0xCD, CMP_ABSX = 0xDD, CMP_ABSY = 0xD9, CMP_INDX = 0xC1, CMP_INDY = 0xD1, CPX_IMM = 0xE0, CPX_ZP = 0xE4, CPX_ABS = 0xEC, CPY_IMM = 0xC0, CPY_ZP = 0xC4, CPY_ABS = 0xCC, INX = 0xE8, INY = 0xC8, INC_ZP = 0xE6, INC_ZPX = 0xF6, INC_ABS = 0xEE, INC_ABSX = 0xFE, DEX = 0xCA, DEY = 0x88, DEC_ZP = 0xC6, DEC_ZPX = 0xD6, DEC_ABS = 0xCE, DEC_ABSX = 0xDE, CLC = 0x18, CLD = 0xD8, CLI = 0x58, CLV = 0xB8, SEC = 0x38, SED = 0xF8, SEI = 0x78, ASL_ACC = 0x0A, ASL_ZP = 0x06, ASL_ZPX = 0x16, ASL_ABS = 0x0E, ASL_ABSX = 0x1E, LSR_ACC = 0x4A, LSR_ZP = 0x46, LSR_ZPX = 0x56, LSR_ABS = 0x4E, LSR_ABSX = 0x5E, ROL_ACC = 0x2A, ROL_ZP = 0x26, ROL_ZPX = 0x36, ROL_ABS = 0x2E, ROL_ABSX = 0x3E, ROR_ACC = 0x6A, ROR_ZP = 0x66, ROR_ZPX = 0x76, ROR_ABS = 0x6E, ROR_ABSX = 0x7E, BCC = 0x90, BCS = 0xB0, BEQ = 0xF0, BMI = 0x30, BNE = 0xD0, BPL = 0x10, BVC = 0x50, BVS = 0x70, JMP_ABS = 0x4C, JMP_IND = 0x6C, JSR_ABS = 0x20, RTS = 0x60, BRK = 0x00, RTI = 0x40, NOP = 0xEA, }; pub fn init() CPU { var self = CPU{ .PC = undefined, .PS = undefined, .regs = undefined, .memory = undefined, .ticks = undefined, }; self.reset(INITIAL_ADDRESS); return self; } pub fn reset(self: *CPU, address: Type.Word) void { self.PC = address; self.PS.clear(); self.regs[SP] = 0xFF; self.regs[A] = 0; self.regs[X] = 0; self.regs[Y] = 0; self.memory.clear(); self.ticks = 0; } pub fn run(self: *CPU, limit: u32) u32 { const start = self.ticks; while ((self.ticks - start) < limit) { const op = @intToEnum(OP, self.readByte(self.PC)); self.PC += 1; switch (op) { OP.LDA_IMM => self.fetch(A, .Immediate), OP.LDA_ZP => self.fetch(A, .ZeroPage), OP.LDA_ZPX => self.fetch(A, .ZeroPageX), OP.LDA_ABS => self.fetch(A, .Absolute), OP.LDA_ABSX => self.fetch(A, .AbsoluteX), OP.LDA_ABSY => self.fetch(A, .AbsoluteY), OP.LDA_INDX => self.fetch(A, .IndirectX), OP.LDA_INDY => self.fetch(A, .IndirectY), OP.LDX_IMM => self.fetch(X, .Immediate), OP.LDX_ZP => self.fetch(X, .ZeroPage), OP.LDX_ZPY => self.fetch(X, .ZeroPageY), OP.LDX_ABS => self.fetch(X, .Absolute), OP.LDX_ABSY => self.fetch(X, .AbsoluteY), OP.LDY_IMM => self.fetch(Y, .Immediate), OP.LDY_ZP => self.fetch(Y, .ZeroPage), OP.LDY_ZPX => self.fetch(Y, .ZeroPageX), OP.LDY_ABS => self.fetch(Y, .Absolute), OP.LDY_ABSX => self.fetch(Y, .AbsoluteX), OP.STA_ZP => self.store(A, .ZeroPage), OP.STA_ZPX => self.store(A, .ZeroPageX), OP.STA_ABS => self.store(A, .Absolute), OP.STA_ABSX => self.store(A, .AbsoluteX), OP.STA_ABSY => self.store(A, .AbsoluteY), OP.STA_INDX => self.store(A, .IndirectX), OP.STA_INDY => self.store(A, .IndirectY), OP.STX_ZP => self.store(X, .ZeroPage), OP.STX_ZPY => self.store(X, .ZeroPageY), OP.STX_ABS => self.store(X, .Absolute), OP.STY_ZP => self.store(Y, .ZeroPage), OP.STY_ZPX => self.store(Y, .ZeroPageX), OP.STY_ABS => self.store(Y, .Absolute), OP.TAX => self.transfer(A, X, true), OP.TAY => self.transfer(A, Y, true), OP.TXA => self.transfer(X, A, true), OP.TYA => self.transfer(Y, A, true), OP.TSX => self.transfer(SP, X, true), OP.TXS => self.transfer(X, SP, false), OP.PHA => self.pushRegisterToStack(A), OP.PHP => self.pushPSToStack(), OP.PLA => self.popRegisterFromStack(A), OP.PLP => self.popPSFromStack(true), OP.AND_IMM => self.bitOp(.And, A, .Immediate), OP.AND_ZP => self.bitOp(.And, A, .ZeroPage), OP.AND_ZPX => self.bitOp(.And, A, .ZeroPageX), OP.AND_ABS => self.bitOp(.And, A, .Absolute), OP.AND_ABSX => self.bitOp(.And, A, .AbsoluteX), OP.AND_ABSY => self.bitOp(.And, A, .AbsoluteY), OP.AND_INDX => self.bitOp(.And, A, .IndirectX), OP.AND_INDY => self.bitOp(.And, A, .IndirectY), OP.EOR_IMM => self.bitOp(.ExclusiveOr, A, .Immediate), OP.EOR_ZP => self.bitOp(.ExclusiveOr, A, .ZeroPage), OP.EOR_ZPX => self.bitOp(.ExclusiveOr, A, .ZeroPageX), OP.EOR_ABS => self.bitOp(.ExclusiveOr, A, .Absolute), OP.EOR_ABSX => self.bitOp(.ExclusiveOr, A, .AbsoluteX), OP.EOR_ABSY => self.bitOp(.ExclusiveOr, A, .AbsoluteY), OP.EOR_INDX => self.bitOp(.ExclusiveOr, A, .IndirectX), OP.EOR_INDY => self.bitOp(.ExclusiveOr, A, .IndirectY), OP.ORA_IMM => self.bitOp(.InclusiveOr, A, .Immediate), OP.ORA_ZP => self.bitOp(.InclusiveOr, A, .ZeroPage), OP.ORA_ZPX => self.bitOp(.InclusiveOr, A, .ZeroPageX), OP.ORA_ABS => self.bitOp(.InclusiveOr, A, .Absolute), OP.ORA_ABSX => self.bitOp(.InclusiveOr, A, .AbsoluteX), OP.ORA_ABSY => self.bitOp(.InclusiveOr, A, .AbsoluteY), OP.ORA_INDX => self.bitOp(.InclusiveOr, A, .IndirectX), OP.ORA_INDY => self.bitOp(.InclusiveOr, A, .IndirectY), OP.BIT_ZP => self.bitOp(.Bit, A, .ZeroPage), OP.BIT_ABS => self.bitOp(.Bit, A, .Absolute), OP.ADC_IMM => self.numOp(.Add, A, .Immediate), OP.ADC_ZP => self.numOp(.Add, A, .ZeroPage), OP.ADC_ZPX => self.numOp(.Add, A, .ZeroPageX), OP.ADC_ABS => self.numOp(.Add, A, .Absolute), OP.ADC_ABSX => self.numOp(.Add, A, .AbsoluteX), OP.ADC_ABSY => self.numOp(.Add, A, .AbsoluteY), OP.ADC_INDX => self.numOp(.Add, A, .IndirectX), OP.ADC_INDY => self.numOp(.Add, A, .IndirectY), OP.SBC_IMM => self.numOp(.Subtract, A, .Immediate), OP.SBC_ZP => self.numOp(.Subtract, A, .ZeroPage), OP.SBC_ZPX => self.numOp(.Subtract, A, .ZeroPageX), OP.SBC_ABS => self.numOp(.Subtract, A, .Absolute), OP.SBC_ABSX => self.numOp(.Subtract, A, .AbsoluteX), OP.SBC_ABSY => self.numOp(.Subtract, A, .AbsoluteY), OP.SBC_INDX => self.numOp(.Subtract, A, .IndirectX), OP.SBC_INDY => self.numOp(.Subtract, A, .IndirectY), OP.CMP_IMM => self.compareRegister(A, .Immediate), OP.CMP_ZP => self.compareRegister(A, .ZeroPage), OP.CMP_ZPX => self.compareRegister(A, .ZeroPageX), OP.CMP_ABS => self.compareRegister(A, .Absolute), OP.CMP_ABSX => self.compareRegister(A, .AbsoluteX), OP.CMP_ABSY => self.compareRegister(A, .AbsoluteY), OP.CMP_INDX => self.compareRegister(A, .IndirectX), OP.CMP_INDY => self.compareRegister(A, .IndirectY), OP.CPX_IMM => self.compareRegister(X, .Immediate), OP.CPX_ZP => self.compareRegister(X, .ZeroPage), OP.CPX_ABS => self.compareRegister(X, .Absolute), OP.CPY_IMM => self.compareRegister(Y, .Immediate), OP.CPY_ZP => self.compareRegister(Y, .ZeroPage), OP.CPY_ABS => self.compareRegister(Y, .Absolute), OP.INX => self.incDecReg(.Increment, X), OP.INY => self.incDecReg(.Increment, Y), OP.INC_ZP => self.incDecMem(.Increment, .ZeroPage), OP.INC_ZPX => self.incDecMem(.Increment, .ZeroPageX), OP.INC_ABS => self.incDecMem(.Increment, .Absolute), OP.INC_ABSX => self.incDecMem(.Increment, .AbsoluteX), OP.DEX => self.incDecReg(.Decrement, X), OP.DEY => self.incDecReg(.Decrement, Y), OP.DEC_ZP => self.incDecMem(.Decrement, .ZeroPage), OP.DEC_ZPX => self.incDecMem(.Decrement, .ZeroPageX), OP.DEC_ABS => self.incDecMem(.Decrement, .Absolute), OP.DEC_ABSX => self.incDecMem(.Decrement, .AbsoluteX), OP.CLC => self.clearSetBit(.Clear, .Carry), OP.CLD => self.clearSetBit(.Clear, .Decimal), OP.CLI => self.clearSetBit(.Clear, .Interrupt), OP.CLV => self.clearSetBit(.Clear, .Overflow), OP.SEC => self.clearSetBit(.Set, .Carry), OP.SED => self.clearSetBit(.Set, .Decimal), OP.SEI => self.clearSetBit(.Set, .Interrupt), OP.ASL_ACC => self.displaceReg(.ShiftLeft, A), OP.ASL_ZP => self.displaceMem(.ShiftLeft, .ZeroPage), OP.ASL_ZPX => self.displaceMem(.ShiftLeft, .ZeroPageX), OP.ASL_ABS => self.displaceMem(.ShiftLeft, .Absolute), OP.ASL_ABSX => self.displaceMem(.ShiftLeft, .AbsoluteX), OP.LSR_ACC => self.displaceReg(.ShiftRight, A), OP.LSR_ZP => self.displaceMem(.ShiftRight, .ZeroPage), OP.LSR_ZPX => self.displaceMem(.ShiftRight, .ZeroPageX), OP.LSR_ABS => self.displaceMem(.ShiftRight, .Absolute), OP.LSR_ABSX => self.displaceMem(.ShiftRight, .AbsoluteX), OP.ROL_ACC => self.displaceReg(.RotateLeft, A), OP.ROL_ZP => self.displaceMem(.RotateLeft, .ZeroPage), OP.ROL_ZPX => self.displaceMem(.RotateLeft, .ZeroPageX), OP.ROL_ABS => self.displaceMem(.RotateLeft, .Absolute), OP.ROL_ABSX => self.displaceMem(.RotateLeft, .AbsoluteX), OP.ROR_ACC => self.displaceReg(.RotateRight, A), OP.ROR_ZP => self.displaceMem(.RotateRight, .ZeroPage), OP.ROR_ZPX => self.displaceMem(.RotateRight, .ZeroPageX), OP.ROR_ABS => self.displaceMem(.RotateRight, .Absolute), OP.ROR_ABSX => self.displaceMem(.RotateRight, .AbsoluteX), OP.BCC => self.branchOnBit(Status.Name.Carry, .Clear), OP.BCS => self.branchOnBit(Status.Name.Carry, .Set), OP.BEQ => self.branchOnBit(Status.Name.Zero, .Set), OP.BMI => self.branchOnBit(Status.Name.Negative, .Set), OP.BNE => self.branchOnBit(Status.Name.Zero, .Clear), OP.BPL => self.branchOnBit(Status.Name.Negative, .Clear), OP.BVC => self.branchOnBit(Status.Name.Overflow, .Clear), OP.BVS => self.branchOnBit(Status.Name.Overflow, .Set), OP.JMP_ABS => self.jumpToAddress(.Absolute, false), OP.JMP_IND => self.jumpToAddress(.Indirect, false), OP.JSR_ABS => self.jumpToAddress(.Absolute, true), OP.RTS => self.returnToAddress(), OP.BRK => self.forceInterrupt(), OP.RTI => self.returnFromInterrupt(), OP.NOP => self.tick(), } } const used = self.ticks - start; return used; } fn fetch(self: *CPU, register: usize, mode: AddressingMode) void { const address = self.computeAddress(mode, false); const value = self.readByte(address); self.regs[register] = value; self.setNZ(self.regs[register]); } fn store(self: *CPU, register: usize, mode: AddressingMode) void { const address = self.computeAddress(mode, false); self.writeByte(address, self.regs[register]); } fn transfer(self: *CPU, source: usize, target: usize, flags: bool) void { self.regs[target] = self.regs[source]; if (flags) { self.setNZ(self.regs[target]); } self.tick(); } fn pushRegisterToStack(self: *CPU, register: usize) void { const pushed = self.regs[register]; self.pushByte(pushed); self.tick(); } fn popRegisterFromStack(self: *CPU, register: usize) void { const popped = self.popByte(true); self.regs[register] = popped; self.setNZ(popped); self.tick(); } fn pushPSToStack(self: *CPU) void { var pushed = self.PS; pushed.bits.B = 1; pushed.bits.U = 1; self.pushByte(pushed.byte); self.tick(); } fn popPSFromStack(self: *CPU, doTick: bool) void { const popped = self.popByte(doTick); self.PS.byte = popped; self.PS.bits.B = 0; self.PS.bits.U = 0; if (doTick) { self.tick(); } } fn pushByte(self: *CPU, value: Type.Byte) void { const address = @as(Type.Word, STACK_BASE) + self.regs[SP]; self.writeByte(address, value); self.regs[SP] -%= 1; } fn pushWord(self: *CPU, value: Type.Word) void { const hi = @as(Type.Word, value >> 8); const lo = @as(Type.Word, value & 0xFF); self.pushByte(@intCast(Type.Byte, hi)); self.pushByte(@intCast(Type.Byte, lo)); } fn popByte(self: *CPU, doTick: bool) Type.Byte { self.regs[SP] +%= 1; const address = @as(Type.Word, STACK_BASE) + self.regs[SP]; const value = self.readByte(address); if (doTick) { self.tick(); } return value; } fn popWord(self: *CPU) Type.Word { const lo = @as(Type.Word, self.popByte(false)); self.tick(); const hi = @as(Type.Word, self.popByte(false)) << 8; self.tick(); const value = hi | lo; return value; } fn bitOp(self: *CPU, op: BitOp, register: usize, mode: AddressingMode) void { const address = self.computeAddress(mode, false); const value = self.readByte(address); const result = switch (op) { .And, .Bit => self.regs[register] & value, .InclusiveOr => self.regs[register] | value, .ExclusiveOr => self.regs[register] ^ value, }; if (op == .Bit) { self.PS.bits.N = if ((value & 0b10000000) > 0) 1 else 0; self.PS.bits.V = if ((value & 0b01000000) > 0) 1 else 0; self.PS.bits.Z = if ((result | 0b00000000) > 0) 0 else 1; } else { self.setNZ(result); self.regs[register] = result; } } fn numOp(self: *CPU, op: NumOp, register: usize, mode: AddressingMode) void { const address = self.computeAddress(mode, false); const value = self.readByte(address); switch (op) { .Add => self.addWithCarry(register, value), .Subtract => self.addWithCarry(register, ~value), } } fn addWithCarry(self: *CPU, register: usize, value: Type.Byte) void { const reg: Type.Word = self.regs[register]; const val: Type.Word = value; const car: Type.Word = if (self.PS.bits.C > 0) 1 else 0; const result = reg + val + car; self.PS.bits.C = if (result > 0xFF) 1 else 0; self.PS.bits.V = if (((~(reg ^ val)) & (result ^ val) & 0x80) > 0) 1 else 0; // std.debug.print("{x} + {x} + {x} = {x}\n", .{ reg, val, car, result }); self.regs[register] = @intCast(Type.Byte, result & 0xFF); self.setNZ(self.regs[register]); } fn incDecReg(self: *CPU, op: IncDecOp, register: usize) void { switch (op) { .Increment => self.regs[register] +%= 1, .Decrement => self.regs[register] -%= 1, } self.setNZ(self.regs[register]); self.tick(); } fn incDecMem(self: *CPU, op: IncDecOp, mode: AddressingMode) void { const address = self.computeAddress(mode, true); var value = self.readByte(address); switch (op) { .Increment => value +%= 1, .Decrement => value -%= 1, } self.writeByte(address, value); self.setNZ(value); self.tick(); } fn clearSetBit(self: *CPU, op: ClearSet, bit: Status.Name) void { const value: Type.Bit = switch (op) { .Clear => 0, .Set => 1, }; self.PS.setBitByName(bit, value); self.tick(); } fn displaceReg(self: *CPU, op: DisplaceOp, register: usize) void { self.regs[register] = self.displaceByte(op, self.regs[register]); } fn displaceMem(self: *CPU, op: DisplaceOp, mode: AddressingMode) void { const address = self.computeAddress(mode, true); var value = self.readByte(address); value = self.displaceByte(op, value); self.writeByte(address, value); } fn displaceByte(self: *CPU, op: DisplaceOp, value: Type.Byte) Type.Byte { var displaced = value; switch (op) { .ShiftLeft => { self.PS.bits.C = if ((displaced & 0b10000000) > 0) 1 else 0; displaced <<= 1; }, .ShiftRight => { self.PS.bits.C = if ((displaced & 0b00000001) > 0) 1 else 0; displaced >>= 1; }, .RotateLeft => { const oldC = self.PS.bits.C; self.PS.bits.C = if ((displaced & 0b10000000) > 0) 1 else 0; displaced <<= 1; if (oldC > 0) { displaced |= 1; } }, .RotateRight => { const oldC = self.PS.bits.C; self.PS.bits.C = if ((displaced & 0b00000001) > 0) 1 else 0; displaced >>= 1; if (oldC > 0) { displaced |= 0b10000000; } }, } self.setNZ(displaced); self.tick(); return displaced; } fn branchOnBit(self: *CPU, bit: Status.Name, state: ClearSet) void { const current = self.PS.getBitByName(bit); const delta = @bitCast(i8, self.readByte(self.PC)); self.PC += 1; const branch = switch (state) { .Clear => current == 0, .Set => current > 0, }; if (branch) { self.tick(); const newPC = @bitCast(Type.Word, @bitCast(i16, self.PC) + delta); if (!samePage(self.PC, newPC)) { self.tick(); } self.PC = newPC; } } fn jumpToAddress(self: *CPU, mode: AddressingMode, pushReturn: bool) void { // http://www.obelisk.me.uk/6502/reference.html#JMP // An original 6502 does not correctly fetch the target address if // the indirect vector falls on a page boundary (e.g. $xxFF where xx is // any value from $00 to $FF). In this case fetches the LSB from $xxFF // as expected but takes the MSB from $xx00. This is fixed in some // later chips like the 65SC02 so for compatibility always ensure the // indirect vector is not at the end of the page. const address = self.computeAddress(mode, false); if (pushReturn) { self.pushWord(self.PC - 1); self.tick(); } self.PC = address; } fn returnToAddress(self: *CPU) void { self.PC = self.popWord() + 1; self.tick(); } fn compareRegister(self: *CPU, register: usize, mode: AddressingMode) void { const address = self.computeAddress(mode, false); const value = self.readByte(address); self.PS.bits.C = if (self.regs[register] >= value) 1 else 0; self.PS.bits.Z = if (self.regs[register] == value) 1 else 0; self.PS.bits.N = if (self.regs[register] < value) 1 else 0; } fn forceInterrupt(self: *CPU) void { const interrupt_vector: Type.Word = 0xFFFE; self.pushWord(self.PC + 1); self.pushPSToStack(); self.PC = self.readWord(interrupt_vector); self.PS.bits.B = 1; self.PS.bits.I = 1; } fn returnFromInterrupt(self: *CPU) void { self.popPSFromStack(false); self.PC = self.popWord(); } fn computeAddress(self: *CPU, mode: AddressingMode, alwaysUseExtra: bool) Type.Word { const address = switch (mode) { .Immediate => blk: { const address = self.PC; self.PC += 1; break :blk address; }, .ZeroPage => blk: { const address = @as(Type.Word, self.readByte(self.PC)); self.PC += 1; break :blk address; }, .ZeroPageX => blk: { var address = @as(Type.Word, self.readByte(self.PC)); self.PC += 1; address +%= self.regs[X]; address &= 0xFF; self.tick(); break :blk address; }, .ZeroPageY => blk: { var address = @as(Type.Word, self.readByte(self.PC)); self.PC += 1; address +%= self.regs[Y]; address &= 0xFF; self.tick(); break :blk address; }, .Absolute => blk: { const address = self.readWord(self.PC); self.PC += 2; break :blk address; }, .AbsoluteX => blk: { const initial = self.readWord(self.PC); self.PC += 2; const final = initial + self.regs[X]; if (alwaysUseExtra or !samePage(initial, final)) { self.tick(); } break :blk final; }, .AbsoluteY => blk: { const initial = self.readWord(self.PC); self.PC += 2; const final = initial + self.regs[Y]; if (alwaysUseExtra or !samePage(initial, final)) { self.tick(); } break :blk final; }, .Indirect => blk: { const initial = self.readWord(self.PC); self.PC += 2; const address = self.readWord(initial); break :blk address; }, .IndirectX => blk: { var address = @as(Type.Word, self.readByte(self.PC)); self.PC += 1; address +%= self.regs[X]; address &= 0xFF; self.tick(); const final = self.readWord(address); break :blk final; }, .IndirectY => blk: { const address = @as(Type.Word, self.readByte(self.PC)); self.PC += 1; const initial = self.readWord(address); const final = initial + self.regs[Y]; if (alwaysUseExtra or !samePage(initial, final)) { self.tick(); } break :blk final; }, }; return address; } fn readByte(self: *CPU, address: Type.Word) Type.Byte { const value = self.memory.data[address]; self.tick(); return value; } fn readWord(self: *CPU, address: Type.Word) Type.Word { const lo = @as(Type.Word, self.readByte(address + 0)); const hi = @as(Type.Word, self.readByte(address + 1)) << 8; const value = hi | lo; return value; } fn writeByte(self: *CPU, address: Type.Word, value: Type.Byte) void { self.memory.data[address] = value; self.tick(); } fn tick(self: *CPU) void { self.ticks += 1; } fn setNZ(self: *CPU, value: Type.Byte) void { self.PS.bits.N = if ((value & 0b10000000) > 0) 1 else 0; self.PS.bits.Z = if ((value | 0b00000000) > 0) 0 else 1; } fn samePage(p1: Type.Word, p2: Type.Word) bool { // Sometimes adding something to an address will incur in an extra tick // ONLY when that caused the address to cross onto another page. return (p1 & 0xFF00) == (p2 & 0xFF00); } }; // ========================================================= const TEST_ADDRESS = 0x4433; test "create CPU" { var cpu = CPU.init(); testing.expect(cpu.PC == CPU.INITIAL_ADDRESS); cpu.reset(TEST_ADDRESS); testing.expect(cpu.PC == TEST_ADDRESS); } fn test_load_register(cpu: *CPU, register: usize, address: Type.Word, ticks: u32) void { const Data = struct { v: Type.Byte, N: Type.Bit, Z: Type.Bit, }; const data = [_]Data{ .{ .v = 0x11, .N = 0, .Z = 0 }, .{ .v = 0xF0, .N = 1, .Z = 0 }, .{ .v = 0x00, .N = 0, .Z = 1 }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.memory.data[address] = d.v; // put value in memory address const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers cpu.regs[register] = 0; // set desired register to 0 cpu.PS.byte = 0; // set PS to 0 const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.regs[register] == d.v); // got correct value in register? testing.expect(cpu.PS.bits.N == d.N); // got correct N bit? testing.expect(cpu.PS.bits.Z == d.Z); // got correct Z bit? // other bits didn't change? testing.expect(cpu.PS.bits.C == prevPS.bits.C); testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); testing.expect(cpu.PS.bits.V == prevPS.bits.V); // registers either got set or didn't change? testing.expect(register == CPU.A or cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(register == CPU.X or cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(register == CPU.Y or cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(register == CPU.SP or cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_save_register(cpu: *CPU, register: usize, address: Type.Word, ticks: u32) void { const Data = struct { v: Type.Byte, }; const data = [_]Data{ .{ .v = 0x11 }, .{ .v = 0xF0 }, .{ .v = 0x00 }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.regs[register] = d.v; // put value in register const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers cpu.memory.data[address] = 0; // set desired address to 0 cpu.PS.byte = 0; // set PS to 0 const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.memory.data[address] == d.v); // got correct value in memory? testing.expect(cpu.PS.byte == prevPS.byte); // PS didn't change? // registers didn't change? testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_transfer_register(cpu: *CPU, source: usize, target: usize, flags: bool, ticks: u32) void { const Data = struct { v: Type.Byte, N: Type.Bit, Z: Type.Bit, }; const data = [_]Data{ .{ .v = 0x11, .N = 0, .Z = 0 }, .{ .v = 0xF0, .N = 1, .Z = 0 }, .{ .v = 0x00, .N = 0, .Z = 1 }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.regs[source] = d.v; // put value in source register const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers cpu.regs[target] = 0; // set target register to 0 cpu.PS.byte = 0; // set PS to 0 const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.regs[target] == d.v); // got correct value in target registry? if (flags) { testing.expect(cpu.PS.bits.N == d.N); // got correct N bit? testing.expect(cpu.PS.bits.Z == d.Z); // got correct Z bit? } else { testing.expect(cpu.PS.bits.N == prevPS.bits.N); testing.expect(cpu.PS.bits.Z == prevPS.bits.Z); } // other bits didn't change? testing.expect(cpu.PS.bits.C == prevPS.bits.C); testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); testing.expect(cpu.PS.bits.V == prevPS.bits.V); // registers either got set or didn't change? testing.expect(target == CPU.A or cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(target == CPU.X or cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(target == CPU.Y or cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(target == CPU.SP or cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_push_register(cpu: *CPU, register: usize, ticks: u32) void { const Data = struct { v: Type.Byte, }; const data = [_]Data{ .{ .v = 0x11 }, .{ .v = 0xF0 }, .{ .v = 0x00 }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.PS.byte = 0; // set PS to 0 cpu.regs[register] = d.v; // put value in register const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP] - 1); // did SP move? const address = @as(Type.Word, CPU.STACK_BASE) + prevRegs[CPU.SP]; testing.expect(cpu.memory.data[address] == d.v); // did the value get pushed? // none of the bits changed? testing.expect(cpu.PS.byte == prevPS.byte); // registers didn't change? testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); } } fn test_push_status(cpu: *CPU, ticks: u32) void { const Data = struct { v: Type.Byte, }; const data = [_]Data{ .{ .v = 0x11 }, .{ .v = 0xF0 }, .{ .v = 0x00 }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.PS.byte = d.v; // put value in PS var pushed = cpu.PS; pushed.setBitByName(.Break, 1); pushed.setBitByName(.UNUSED, 1); const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP] - 1); // did SP move? const address = @as(Type.Word, CPU.STACK_BASE) + prevRegs[CPU.SP]; testing.expect(cpu.memory.data[address] == pushed.byte); // did the value get pushed? // none of the bits changed? testing.expect(cpu.PS.byte == prevPS.byte); // registers didn't change? testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); } } fn test_pop_register(cpu: *CPU, register: usize, ticks: u32) void { const Data = struct { v: Type.Byte, N: Type.Bit, Z: Type.Bit, }; const data = [_]Data{ .{ .v = 0x11, .N = 0, .Z = 0 }, .{ .v = 0xF0, .N = 1, .Z = 0 }, .{ .v = 0x00, .N = 0, .Z = 1 }, }; var SP: Type.Byte = 0xFF; for (data) |d| { const address = @as(Type.Word, CPU.STACK_BASE) + SP; cpu.memory.data[address] = d.v; // set value in stack SP -%= 1; } cpu.regs[CPU.SP] = SP; for (data) |d, p| { const pos = data.len - 1 - p; cpu.PC = TEST_ADDRESS; cpu.PS.byte = 0; // set PS to 0 cpu.regs[register] = 0; // set register to 0 const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP] + 1); // did SP move? const address = @as(Type.Word, CPU.STACK_BASE) + prevRegs[CPU.SP]; testing.expect(cpu.regs[register] == data[pos].v); // did the value get popped? testing.expect(cpu.PS.bits.N == data[pos].N); // got correct N bit? testing.expect(cpu.PS.bits.Z == data[pos].Z); // got correct Z bit? // other bits didn't change? testing.expect(cpu.PS.bits.C == prevPS.bits.C); testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); testing.expect(cpu.PS.bits.V == prevPS.bits.V); // registers didn't change? testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); } testing.expect(cpu.regs[CPU.SP] == 0xFF); } fn test_pop_status(cpu: *CPU, ticks: u32) void { const Data = struct { v: Type.Byte, N: Type.Bit, Z: Type.Bit, }; const data = [_]Data{ .{ .v = 0x11, .N = 0, .Z = 0 }, .{ .v = 0xF0, .N = 1, .Z = 0 }, .{ .v = 0x00, .N = 0, .Z = 1 }, }; var SP: Type.Byte = 0xFF; for (data) |d| { const address = @as(Type.Word, CPU.STACK_BASE) + SP; cpu.memory.data[address] = d.v; // set value in stack SP -%= 1; } cpu.regs[CPU.SP] = SP; for (data) |d, p| { const pos = data.len - 1 - p; cpu.PC = TEST_ADDRESS; cpu.PS.byte = 0; // set PS to 0 const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); var popped = cpu.PS; popped.byte = data[pos].v; // did the value get popped? popped.setBitByName(.Break, 0); popped.setBitByName(.UNUSED, 0); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP] + 1); // did SP move? const address = @as(Type.Word, CPU.STACK_BASE) + prevRegs[CPU.SP]; testing.expect(cpu.PS.byte == popped.byte); // did the value get popped? // registers didn't change? testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); } testing.expect(cpu.regs[CPU.SP] == 0xFF); } fn test_bitop_register(cpu: *CPU, op: CPU.BitOp, register: usize, address: Type.Word, ticks: u32) void { const Data = struct { m: Type.Byte, r: Type.Byte, }; const data = [_]Data{ .{ .m = 0b00110001, .r = 0b10101010, }, .{ .m = 0b01010101, .r = 0b10101010, }, .{ .m = 0b10110011, .r = 0b10101010, }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.memory.data[address] = d.m; // put value in memory address const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers cpu.regs[register] = d.r; // set desired register cpu.PS.byte = 0; // set PS to 0 const afterR: Type.Byte = switch (op) { .And, .Bit => d.m & d.r, .InclusiveOr => d.m | d.r, .ExclusiveOr => d.m ^ d.r, }; const used = cpu.run(ticks); testing.expect(used == ticks); const afterZ: Type.Bit = if ((afterR | 0b00000000) > 0) 0 else 1; testing.expect(cpu.PS.bits.Z == afterZ); // got correct N bit? if (op == .Bit) { const afterN: Type.Bit = if ((d.m & 0b10000000) > 0) 1 else 0; const afterV: Type.Bit = if ((d.m & 0b01000000) > 0) 1 else 0; testing.expect(cpu.PS.bits.N == afterN); // got correct N bit? testing.expect(cpu.PS.bits.V == afterV); // got correct V bit? } else { const afterN: Type.Bit = if ((afterR & 0b10000000) > 0) 1 else 0; testing.expect(cpu.PS.bits.N == afterN); // got correct N bit? testing.expect(cpu.regs[register] == afterR); // got correct after value in register? } // other bits didn't change? testing.expect(cpu.PS.bits.C == prevPS.bits.C); testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); // registers either got set or didn't change? testing.expect(register == CPU.A or cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(register == CPU.X or cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(register == CPU.Y or cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(register == CPU.SP or cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_numop_register(cpu: *CPU, op: CPU.NumOp, register: usize, address: Type.Word, ticks: u32) void { const Data = struct { oC: Type.Bit, oR: Type.Byte, oM: Type.Byte, aR: Type.Byte, sR: Type.Byte, aC: Type.Bit, aZ: Type.Bit, aV: Type.Bit, aN: Type.Bit, sC: Type.Bit, sZ: Type.Bit, sV: Type.Bit, sN: Type.Bit, }; const data = [_]Data{ .{ .oC = 0, .oR = 0b00000000, .oM = 0b00000000, .aR = 0b00000000, .sR = 0b11111111, .aC = 0, .aZ = 1, .aV = 0, .aN = 0, .sC = 0, .sZ = 0, .sV = 0, .sN = 1, }, .{ .oC = 1, .oR = 0b00000000, .oM = 0b00000000, .aR = 0b00000001, .sR = 0b00000000, .aC = 0, .aZ = 0, .aV = 0, .aN = 0, .sC = 1, .sZ = 1, .sV = 0, .sN = 0, }, .{ .oC = 0, .oR = 0b00100100, // 36 .oM = 0b00001101, // 13 .aR = 0b00110001, // 49 .sR = 0b00010110, // 22 .aC = 0, .aZ = 0, .aV = 0, .aN = 0, .sC = 1, .sZ = 0, .sV = 0, .sN = 0, }, .{ .oC = 1, .oR = 0b00100100, // 36 .oM = 0b00001101, // 13 .aR = 0b00110010, // 50 .sR = 0b00010111, // 23 .aC = 0, .aZ = 0, .aV = 0, .aN = 0, .sC = 1, .sZ = 0, .sV = 0, .sN = 0, }, .{ .oC = 0, .oR = 0b01000001, // 65 .oM = 0b01000000, // 64 .aR = 0b10000001, // 129 .sR = 0b00000000, // 0 .aC = 0, .aZ = 0, .aV = 1, .aN = 1, .sC = 1, .sZ = 1, .sV = 0, .sN = 0, }, .{ .oC = 1, .oR = 0b01000010, // 66 .oM = 0b01000000, // 64 .aR = 0b10000011, // 131 .sR = 0b00000010, // 2 .aC = 0, .aZ = 0, .aV = 1, .aN = 1, .sC = 1, .sZ = 0, .sV = 0, .sN = 0, }, .{ .oC = 0, .oR = 0b10000001, // 129 .oM = 0b10000001, // 129 .aR = 0b00000010, // 2 .sR = 0b11111111, // -1 .aC = 1, .aZ = 0, .aV = 1, .aN = 0, .sC = 0, .sZ = 0, .sV = 0, .sN = 1, }, .{ .oC = 1, .oR = 0b10000001, // 129 .oM = 0b10000001, // 129 .aR = 0b00000011, // 3 .sR = 0b00000000, // 0 .aC = 1, .aZ = 0, .aV = 1, .aN = 0, .sC = 1, .sZ = 1, .sV = 0, .sN = 0, }, .{ .oC = 0, .oR = 0b00001001, // 9 .oM = 0b11111100, // -4 .aR = 0b00000101, // 5 .sR = 0b00001100, // 12 .aC = 1, .aZ = 0, .aV = 0, .aN = 0, .sC = 0, .sZ = 0, .sV = 0, .sN = 0, }, .{ .oC = 1, .oR = 0b00001001, // 9 .oM = 0b11111100, // -4 .aR = 0b00000110, // 6 .sR = 0b00001101, // 13 .aC = 1, .aZ = 0, .aV = 0, .aN = 0, .sC = 0, .sZ = 0, .sV = 0, .sN = 0, }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.memory.data[address] = d.oM; // put value in memory address const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers cpu.regs[register] = d.oR; // set desired register cpu.PS.bits.C = d.oC; // set carry const used = cpu.run(ticks); testing.expect(used == ticks); switch (op) { .Add => { testing.expect(cpu.regs[register] == d.aR); // got correct result? testing.expect(cpu.PS.bits.C == d.aC); // got correct C bit? testing.expect(cpu.PS.bits.Z == d.aZ); // got correct Z bit? testing.expect(cpu.PS.bits.V == d.aV); // got correct V bit? testing.expect(cpu.PS.bits.N == d.aN); // got correct N bit? }, .Subtract => { testing.expect(cpu.regs[register] == d.sR); // got correct result? testing.expect(cpu.PS.bits.C == d.sC); // got correct C bit? testing.expect(cpu.PS.bits.Z == d.sZ); // got correct Z bit? testing.expect(cpu.PS.bits.V == d.sV); // got correct V bit? testing.expect(cpu.PS.bits.N == d.sN); // got correct N bit? }, } // other bits didn't change? testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); // registers either got set or didn't change? testing.expect(register == CPU.A or cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(register == CPU.X or cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(register == CPU.Y or cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(register == CPU.SP or cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_compare_register(cpu: *CPU, register: usize, address: Type.Word, ticks: u32) void { const Data = struct { R: Type.Byte, M: Type.Byte, C: Type.Bit, Z: Type.Bit, N: Type.Bit, }; const data = [_]Data{ .{ .R = 0x43, .M = 0x33, .C = 1, .Z = 0, .N = 0, }, .{ .R = 0x33, .M = 0x33, .C = 1, .Z = 1, .N = 0, }, .{ .R = 0x33, .M = 0x43, .C = 0, .Z = 0, .N = 1, }, }; for (data) |d| { cpu.PC = TEST_ADDRESS; cpu.memory.data[address] = d.M; // put value in memory address cpu.regs[register] = d.R; // set desired register cpu.PS.byte = 0; const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.PS.bits.C == d.C); // got correct C bit? testing.expect(cpu.PS.bits.Z == d.Z); // got correct Z bit? testing.expect(cpu.PS.bits.N == d.N); // got correct N bit? // other bits didn't change? testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); testing.expect(cpu.PS.bits.V == prevPS.bits.V); // registers didn't change? testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_inc_dec(cpu: *CPU, op: CPU.IncDecOp, register: usize, address: Type.Word, ticks: u32) void { const Data = struct { v: Type.Byte, o: CPU.IncDecOp, e: Type.Byte, N: Type.Bit, Z: Type.Bit, }; const data = [_]Data{ .{ .v = 0x11, .o = .Increment, .e = 0x12, .N = 0, .Z = 0 }, .{ .v = 0x11, .o = .Decrement, .e = 0x10, .N = 0, .Z = 0 }, .{ .v = 0xF0, .o = .Increment, .e = 0xF1, .N = 1, .Z = 0 }, .{ .v = 0xF0, .o = .Decrement, .e = 0xEF, .N = 1, .Z = 0 }, .{ .v = 0x00, .o = .Increment, .e = 0x01, .N = 0, .Z = 0 }, .{ .v = 0x00, .o = .Decrement, .e = 0xFF, .N = 1, .Z = 0 }, .{ .v = 0x01, .o = .Increment, .e = 0x02, .N = 0, .Z = 0 }, .{ .v = 0x01, .o = .Decrement, .e = 0x00, .N = 0, .Z = 1 }, .{ .v = 0xFF, .o = .Increment, .e = 0x00, .N = 0, .Z = 1 }, .{ .v = 0xFF, .o = .Decrement, .e = 0xFE, .N = 1, .Z = 0 }, }; for (data) |d| { if (op != d.o) { continue; } cpu.PC = TEST_ADDRESS; if (address == 0) { cpu.regs[register] = d.v; // set desired register } else { cpu.memory.data[address] = d.v; // set desired address } const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers cpu.PS.byte = 0; // set PS to 0 const used = cpu.run(ticks); testing.expect(used == ticks); if (address == 0) { testing.expect(cpu.regs[register] == d.e); } else { testing.expect(cpu.memory.data[address] == d.e); } testing.expect(cpu.PS.bits.N == d.N); // got correct N bit? testing.expect(cpu.PS.bits.Z == d.Z); // got correct Z bit? // other bits didn't change? testing.expect(cpu.PS.bits.C == prevPS.bits.C); testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); testing.expect(cpu.PS.bits.V == prevPS.bits.V); } } fn test_set_bit(cpu: *CPU, op: CPU.ClearSet, bit: Status.Name, ticks: u32) void { cpu.PC = TEST_ADDRESS; switch (op) { .Clear => cpu.PS.setBitByName(bit, 1), .Set => cpu.PS.setBitByName(bit, 0), } const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); switch (op) { .Clear => testing.expect(cpu.PS.getBitByName(bit) == 0), .Set => testing.expect(cpu.PS.getBitByName(bit) == 1), } // other bits didn't change? testing.expect(bit == .Carry or cpu.PS.bits.C == prevPS.bits.C); testing.expect(bit == .Zero or cpu.PS.bits.Z == prevPS.bits.Z); testing.expect(bit == .Interrupt or cpu.PS.bits.I == prevPS.bits.I); testing.expect(bit == .Decimal or cpu.PS.bits.D == prevPS.bits.D); testing.expect(bit == .Break or cpu.PS.bits.B == prevPS.bits.B); testing.expect(bit == .Overflow or cpu.PS.bits.V == prevPS.bits.V); testing.expect(bit == .Negative or cpu.PS.bits.N == prevPS.bits.N); } fn test_branch_bit(cpu: *CPU, bit: Status.Name, state: CPU.ClearSet, ticks: u32) void { const Data = struct { b: Type.Bit, s: CPU.ClearSet, d: u8, x: u32, }; const data = [_]Data{ .{ .b = 0, .s = .Clear, .d = 0x10, .x = 1 }, .{ .b = 0, .s = .Set, .d = 0x10, .x = 0 }, .{ .b = 1, .s = .Clear, .d = 0x10, .x = 0 }, .{ .b = 1, .s = .Set, .d = 0x10, .x = 1 }, .{ .b = 0, .s = .Clear, .d = 0x81, .x = 2 }, .{ .b = 0, .s = .Set, .d = 0x81, .x = 0 }, .{ .b = 1, .s = .Clear, .d = 0x81, .x = 0 }, .{ .b = 1, .s = .Set, .d = 0x81, .x = 2 }, }; for (data) |d| { if (state != d.s) { continue; } cpu.PC = TEST_ADDRESS; cpu.memory.data[TEST_ADDRESS + 1] = d.d; cpu.PS.setBitByName(bit, d.b); const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const expected = ticks + d.x; const used = cpu.run(expected); testing.expect(used == expected); var newPC: Type.Word = TEST_ADDRESS + 2; if (d.x > 0) { newPC = @bitCast(Type.Word, @bitCast(i16, newPC) + @bitCast(i8, d.d)); } testing.expect(cpu.PC == newPC); testing.expect(cpu.PS.byte == prevPS.byte); testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_jmp(cpu: *CPU, address: Type.Word, pushReturn: bool, ticks: u32) void { cpu.PC = TEST_ADDRESS; const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.PC == address); testing.expect(cpu.PS.byte == prevPS.byte); testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); if (pushReturn) { testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP] - 2); } else { testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } } fn test_rts(cpu: *CPU) void { cpu.PC = TEST_ADDRESS; const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const ticks: u32 = 6 + 6; const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.PC == TEST_ADDRESS + 3); testing.expect(cpu.PS.byte == prevPS.byte); testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } fn test_brk(cpu: *CPU) void { cpu.PC = TEST_ADDRESS; cpu.memory.data[0xFFFE] = 0x37; cpu.memory.data[0xFFFF] = 0x41; cpu.PS.bits.B = 0; const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const ticks: u32 = 7; const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.PC == 0x4137); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP] - 3); testing.expect(cpu.PS.bits.B == 1); testing.expect(cpu.PS.bits.I == 1); // other bits didn't change? testing.expect(cpu.PS.bits.C == prevPS.bits.C); testing.expect(cpu.PS.bits.Z == prevPS.bits.Z); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.V == prevPS.bits.V); testing.expect(cpu.PS.bits.N == prevPS.bits.N); testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); } fn test_rti(cpu: *CPU) void { cpu.PC = TEST_ADDRESS; cpu.memory.data[0xFFFE] = 0x37; cpu.memory.data[0xFFFF] = 0x41; cpu.memory.data[0x4137] = 0x40; const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const ticks: u32 = 7 + 6; const used = cpu.run(ticks); testing.expect(used == ticks); testing.expect(cpu.PC == TEST_ADDRESS + 2); testing.expect(cpu.PS.byte == prevPS.byte); testing.expect(cpu.regs[CPU.A] == prevRegs[CPU.A]); testing.expect(cpu.regs[CPU.X] == prevRegs[CPU.X]); testing.expect(cpu.regs[CPU.Y] == prevRegs[CPU.Y]); testing.expect(cpu.regs[CPU.SP] == prevRegs[CPU.SP]); } fn test_displace_bit(cpu: *CPU, op: CPU.DisplaceOp, register: usize, address: Type.Word, ticks: u32) void { const Data = struct { v: Type.Byte, o: CPU.DisplaceOp, e: Type.Byte, oC: Type.Bit, nC: Type.Bit, }; const data = [_]Data{ .{ .v = 0b00000000, .o = .ShiftLeft, .e = 0b00000000, .oC = 0, .nC = 0 }, .{ .v = 0b00000001, .o = .ShiftLeft, .e = 0b00000010, .oC = 0, .nC = 0 }, .{ .v = 0b10000001, .o = .ShiftLeft, .e = 0b00000010, .oC = 0, .nC = 1 }, .{ .v = 0b00000000, .o = .ShiftRight, .e = 0b00000000, .oC = 0, .nC = 0 }, .{ .v = 0b00000001, .o = .ShiftRight, .e = 0b00000000, .oC = 0, .nC = 1 }, .{ .v = 0b10000001, .o = .ShiftRight, .e = 0b01000000, .oC = 0, .nC = 1 }, .{ .v = 0b00000000, .o = .RotateLeft, .e = 0b00000000, .oC = 0, .nC = 0 }, .{ .v = 0b00000000, .o = .RotateLeft, .e = 0b00000001, .oC = 1, .nC = 0 }, .{ .v = 0b00000001, .o = .RotateLeft, .e = 0b00000010, .oC = 0, .nC = 0 }, .{ .v = 0b00000001, .o = .RotateLeft, .e = 0b00000011, .oC = 1, .nC = 0 }, .{ .v = 0b10000001, .o = .RotateLeft, .e = 0b00000010, .oC = 0, .nC = 1 }, .{ .v = 0b10000001, .o = .RotateLeft, .e = 0b00000011, .oC = 1, .nC = 1 }, .{ .v = 0b00000000, .o = .RotateRight, .e = 0b00000000, .oC = 0, .nC = 0 }, .{ .v = 0b00000000, .o = .RotateRight, .e = 0b10000000, .oC = 1, .nC = 0 }, .{ .v = 0b00000001, .o = .RotateRight, .e = 0b00000000, .oC = 0, .nC = 1 }, .{ .v = 0b00000001, .o = .RotateRight, .e = 0b10000000, .oC = 1, .nC = 1 }, .{ .v = 0b10000001, .o = .RotateRight, .e = 0b01000000, .oC = 0, .nC = 1 }, .{ .v = 0b10000001, .o = .RotateRight, .e = 0b11000000, .oC = 1, .nC = 1 }, }; for (data) |d| { if (op != d.o) { continue; } cpu.PC = TEST_ADDRESS; if (address == 0) { cpu.regs[register] = d.v; } else { cpu.memory.data[address] = d.v; } cpu.PS.bits.C = d.oC; const prevPS = cpu.PS; // remember PS const prevRegs = cpu.regs; // remember registers const used = cpu.run(ticks); testing.expect(used == ticks); if (address == 0) { cpu.regs[register] = d.e; } else { cpu.memory.data[address] = d.e; } testing.expect(cpu.PS.bits.C == d.nC); const nZ: Type.Bit = if ((d.e | 0b00000000) > 0) 0 else 1; const nN: Type.Bit = if ((d.e & 0b10000000) > 0) 1 else 0; testing.expect(cpu.PS.bits.Z == nZ); testing.expect(cpu.PS.bits.N == nN); // other bits didn't change? testing.expect(cpu.PS.bits.I == prevPS.bits.I); testing.expect(cpu.PS.bits.D == prevPS.bits.D); testing.expect(cpu.PS.bits.B == prevPS.bits.B); testing.expect(cpu.PS.bits.V == prevPS.bits.V); } } // LDA tests test "run LDA_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xA9; test_load_register(&cpu, CPU.A, TEST_ADDRESS + 1, 2); } test "run LDA_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xA5; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_load_register(&cpu, CPU.A, 0x0011, 3); } test "run LDA_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xB5; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_load_register(&cpu, CPU.A, 0x0011 + 7, 4); } test "run LDA_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xAD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.A, 0x8311, 4); } test "run LDA_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xBD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.A, 0x8311 + 7, 4); } test "run LDA_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xB9; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.A, 0x8311 + 7, 4); } test "run LDA_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xBD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.A, 0x8311 + 0xFE, 5); } test "run LDA_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xB9; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.A, 0x8311 + 0xFE, 5); } test "run LDA_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0xA1; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_load_register(&cpu, CPU.A, 0x2074, 6); } test "run LDA_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0xB1; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_load_register(&cpu, CPU.A, 0x4028 + 0x10, 5); } test "run LDA_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xB1; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_load_register(&cpu, CPU.A, 0x4028 + 0xFE, 6); } // LDX tests test "run LDX_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xA2; test_load_register(&cpu, CPU.X, TEST_ADDRESS + 1, 2); } test "run LDX_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xA6; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_load_register(&cpu, CPU.X, 0x0011, 3); } test "run LDX_ZPY" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xB6; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_load_register(&cpu, CPU.X, 0x0011 + 7, 4); } test "run LDX_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xAE; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.X, 0x8311, 4); } test "run LDX_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xBE; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.X, 0x8311 + 7, 4); } test "run LDX_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xBE; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.X, 0x8311 + 0xFE, 5); } // LDY tests test "run LDY_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xA0; test_load_register(&cpu, CPU.Y, TEST_ADDRESS + 1, 2); } test "run LDY_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xA4; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_load_register(&cpu, CPU.Y, 0x0011, 3); } test "run LDY_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xB4; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_load_register(&cpu, CPU.Y, 0x0011 + 7, 4); } test "run LDY_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xAC; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.Y, 0x8311, 4); } test "run LDY_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xBC; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.Y, 0x8311 + 7, 4); } test "run LDY_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xBC; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_load_register(&cpu, CPU.Y, 0x8311 + 0xFE, 5); } // STA tests test "run STA_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x85; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_save_register(&cpu, CPU.A, 0x0011, 3); } test "run STA_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x95; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_save_register(&cpu, CPU.A, 0x0011 + 7, 4); } test "run STA_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x8D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_save_register(&cpu, CPU.A, 0x8311, 4); } test "run STA_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x9D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_save_register(&cpu, CPU.A, 0x8311 + 7, 4); } test "run STA_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x99; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_save_register(&cpu, CPU.A, 0x8311 + 7, 4); } test "run STA_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x9D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_save_register(&cpu, CPU.A, 0x8311 + 0xFE, 5); } test "run STA_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x99; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_save_register(&cpu, CPU.A, 0x8311 + 0xFE, 5); } test "run STA_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0x81; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_save_register(&cpu, CPU.A, 0x2074, 6); } test "run STA_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0x91; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_save_register(&cpu, CPU.A, 0x4028 + 0x10, 5); } test "run STA_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x91; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_save_register(&cpu, CPU.A, 0x4028 + 0xFE, 6); } // STX tests test "run STX_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x86; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_save_register(&cpu, CPU.X, 0x0011, 3); } test "run STX_ZPY" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x96; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_save_register(&cpu, CPU.X, 0x0011 + 7, 4); } test "run STX_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x8E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_save_register(&cpu, CPU.X, 0x8311, 4); } // STY tests test "run STY_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x84; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_save_register(&cpu, CPU.Y, 0x0011, 3); } test "run STY_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x94; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_save_register(&cpu, CPU.Y, 0x0011 + 7, 4); } test "run STY_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x8C; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_save_register(&cpu, CPU.Y, 0x8311, 4); } // TRANSFER tests test "run TAX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xAA; test_transfer_register(&cpu, CPU.A, CPU.X, true, 2); } test "run TAY" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xA8; test_transfer_register(&cpu, CPU.A, CPU.Y, true, 2); } test "run TXA" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x8A; test_transfer_register(&cpu, CPU.X, CPU.A, true, 2); } test "run TYA" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x98; test_transfer_register(&cpu, CPU.Y, CPU.A, true, 2); } test "run TSX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xBA; test_transfer_register(&cpu, CPU.SP, CPU.X, true, 2); } test "run TXS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x9A; test_transfer_register(&cpu, CPU.X, CPU.SP, false, 2); } // push test "run PHA" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x48; test_push_register(&cpu, CPU.A, 3); } test "run PHP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x08; test_push_status(&cpu, 3); } // pop test "run PLA" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x68; test_pop_register(&cpu, CPU.A, 4); } test "run PLP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x28; test_pop_status(&cpu, 4); } // AND tests test "run AND_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x29; test_bitop_register(&cpu, .And, CPU.A, TEST_ADDRESS + 1, 2); } test "run AND_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x25; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_bitop_register(&cpu, .And, CPU.A, 0x0011, 3); } test "run AND_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x35; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_bitop_register(&cpu, .And, CPU.A, 0x0011 + 7, 4); } test "run AND_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x2D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .And, CPU.A, 0x8311, 4); } test "run AND_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x3D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .And, CPU.A, 0x8311 + 7, 4); } test "run AND_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x39; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .And, CPU.A, 0x8311 + 7, 4); } test "run AND_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x3D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .And, CPU.A, 0x8311 + 0xFE, 5); } test "run AND_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x39; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .And, CPU.A, 0x8311 + 0xFE, 5); } test "run AND_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0x21; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_bitop_register(&cpu, .And, CPU.A, 0x2074, 6); } test "run AND_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0x31; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_bitop_register(&cpu, .And, CPU.A, 0x4028 + 0x10, 5); } test "run AND_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x31; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_bitop_register(&cpu, .And, CPU.A, 0x4028 + 0xFE, 6); } // EOR tests test "run EOR_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x49; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, TEST_ADDRESS + 1, 2); } test "run EOR_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x45; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x0011, 3); } test "run EOR_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x55; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x0011 + 7, 4); } test "run EOR_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x4D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x8311, 4); } test "run EOR_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x5D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x8311 + 7, 4); } test "run EOR_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x59; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x8311 + 7, 4); } test "run EOR_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x5D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x8311 + 0xFE, 5); } test "run EOR_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x59; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x8311 + 0xFE, 5); } test "run EOR_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0x41; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x2074, 6); } test "run EOR_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0x51; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x4028 + 0x10, 5); } test "run EOR_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x51; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_bitop_register(&cpu, .ExclusiveOr, CPU.A, 0x4028 + 0xFE, 6); } // ORA tests test "run ORA_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x09; test_bitop_register(&cpu, .InclusiveOr, CPU.A, TEST_ADDRESS + 1, 2); } test "run ORA_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x05; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x0011, 3); } test "run ORA_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x15; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x0011 + 7, 4); } test "run ORA_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x0D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x8311, 4); } test "run ORA_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x1D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x8311 + 7, 4); } test "run ORA_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x19; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x8311 + 7, 4); } test "run ORA_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x1D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x8311 + 0xFE, 5); } test "run ORA_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x19; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x8311 + 0xFE, 5); } test "run ORA_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0x01; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x2074, 6); } test "run ORA_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0x11; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x4028 + 0x10, 5); } test "run ORA_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x11; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_bitop_register(&cpu, .InclusiveOr, CPU.A, 0x4028 + 0xFE, 6); } // BIT tests test "run BIT_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x24; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_bitop_register(&cpu, .Bit, CPU.A, 0x0011, 3); } test "run BIT_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x2C; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_bitop_register(&cpu, .Bit, CPU.A, 0x8311, 4); } // ADC tests test "run ADC_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x69; test_numop_register(&cpu, .Add, CPU.A, TEST_ADDRESS + 1, 2); } test "run ADC_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x65; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_numop_register(&cpu, .Add, CPU.A, 0x0011, 3); } test "run ADC_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x75; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_numop_register(&cpu, .Add, CPU.A, 0x0011 + 7, 4); } test "run ADC_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x6D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Add, CPU.A, 0x8311, 4); } test "run ADC_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x7D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Add, CPU.A, 0x8311 + 7, 4); } test "run ADC_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x79; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Add, CPU.A, 0x8311 + 7, 4); } test "run ADC_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x7D; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Add, CPU.A, 0x8311 + 0xFE, 5); } test "run ADC_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x79; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Add, CPU.A, 0x8311 + 0xFE, 5); } test "run ADC_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0x61; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_numop_register(&cpu, .Add, CPU.A, 0x2074, 6); } test "run ADC_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0x71; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_numop_register(&cpu, .Add, CPU.A, 0x4028 + 0x10, 5); } test "run ADC_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0x71; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_numop_register(&cpu, .Add, CPU.A, 0x4028 + 0xFE, 6); } // SBC tests test "run SBC_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xE9; test_numop_register(&cpu, .Subtract, CPU.A, TEST_ADDRESS + 1, 2); } test "run SBC_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xE5; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_numop_register(&cpu, .Subtract, CPU.A, 0x0011, 3); } test "run SBC_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xF5; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_numop_register(&cpu, .Subtract, CPU.A, 0x0011 + 7, 4); } test "run SBC_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xED; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Subtract, CPU.A, 0x8311, 4); } test "run SBC_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xFD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Subtract, CPU.A, 0x8311 + 7, 4); } test "run SBC_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xF9; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Subtract, CPU.A, 0x8311 + 7, 4); } test "run SBC_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xFD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Subtract, CPU.A, 0x8311 + 0xFE, 5); } test "run SBC_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xF9; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_numop_register(&cpu, .Subtract, CPU.A, 0x8311 + 0xFE, 5); } test "run SBC_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0xE1; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_numop_register(&cpu, .Subtract, CPU.A, 0x2074, 6); } test "run SBC_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0xF1; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_numop_register(&cpu, .Subtract, CPU.A, 0x4028 + 0x10, 5); } test "run SBC_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xF1; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_numop_register(&cpu, .Subtract, CPU.A, 0x4028 + 0xFE, 6); } // CMP tests test "run CMP_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xC9; test_compare_register(&cpu, CPU.A, TEST_ADDRESS + 1, 2); } test "run CMP_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xC5; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_compare_register(&cpu, CPU.A, 0x0011, 3); } test "run CMP_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xD5; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_compare_register(&cpu, CPU.A, 0x0011 + 7, 4); } test "run CMP_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xCD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_compare_register(&cpu, CPU.A, 0x8311, 4); } test "run CMP_ABSX same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xDD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_compare_register(&cpu, CPU.A, 0x8311 + 7, 4); } test "run CMP_ABSY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xD9; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_compare_register(&cpu, CPU.A, 0x8311 + 7, 4); } test "run CMP_ABSX cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xDD; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_compare_register(&cpu, CPU.A, 0x8311 + 0xFE, 5); } test "run CMP_ABSY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xD9; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_compare_register(&cpu, CPU.A, 0x8311 + 0xFE, 5); } test "run CMP_INDX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 4; cpu.memory.data[TEST_ADDRESS + 0] = 0xC1; cpu.memory.data[TEST_ADDRESS + 1] = 0x20; cpu.memory.data[0x20 + 4 + 0] = 0x74; cpu.memory.data[0x20 + 4 + 1] = 0x20; test_compare_register(&cpu, CPU.A, 0x2074, 6); } test "run CMP_INDY same page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0x10; cpu.memory.data[TEST_ADDRESS + 0] = 0xD1; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_compare_register(&cpu, CPU.A, 0x4028 + 0x10, 5); } test "run CMP_INDY cross page" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.Y] = 0xFE; cpu.memory.data[TEST_ADDRESS + 0] = 0xD1; cpu.memory.data[TEST_ADDRESS + 1] = 0x86; cpu.memory.data[0x86 + 0] = 0x28; cpu.memory.data[0x86 + 1] = 0x40; test_compare_register(&cpu, CPU.A, 0x4028 + 0xFE, 6); } // CPX tests test "run CPX_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xE0; test_compare_register(&cpu, CPU.X, TEST_ADDRESS + 1, 2); } test "run CPX_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xE4; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_compare_register(&cpu, CPU.X, 0x0011, 3); } test "run CPX_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xEC; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_compare_register(&cpu, CPU.X, 0x8311, 4); } // CPY tests test "run CPY_IMM" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xC0; test_compare_register(&cpu, CPU.Y, TEST_ADDRESS + 1, 2); } test "run CPY_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xC4; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_compare_register(&cpu, CPU.Y, 0x0011, 3); } test "run CPY_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xCC; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_compare_register(&cpu, CPU.Y, 0x8311, 4); } // INC tests test "run INC_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xE6; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_inc_dec(&cpu, .Increment, 0, 0x0011, 5); } test "run INC_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xF6; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_inc_dec(&cpu, .Increment, 0, 0x0011 + 7, 6); } test "run INC_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xEE; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_inc_dec(&cpu, .Increment, 0, 0x8311, 6); } test "run INC_ABSX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xFE; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_inc_dec(&cpu, .Increment, 0, 0x8311 + 7, 7); } test "run INCX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xE8; test_inc_dec(&cpu, .Increment, CPU.X, 0, 2); } test "run INCY" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xC8; test_inc_dec(&cpu, .Increment, CPU.Y, 0, 2); } // DEC tests test "run DEC_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xC6; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_inc_dec(&cpu, .Decrement, 0, 0x0011, 5); } test "run DEC_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xD6; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_inc_dec(&cpu, .Decrement, 0, 0x0011 + 7, 6); } test "run DEC_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xCE; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_inc_dec(&cpu, .Decrement, 0, 0x8311, 6); } test "run DEC_ABSX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0xDE; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_inc_dec(&cpu, .Decrement, 0, 0x8311 + 7, 7); } test "run DECX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xCA; test_inc_dec(&cpu, .Decrement, CPU.X, 0, 2); } test "run DECY" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x88; test_inc_dec(&cpu, .Decrement, CPU.Y, 0, 2); } // CLR / SET tests test "run CLC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x18; test_set_bit(&cpu, .Clear, .Carry, 2); } test "run CLD" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xD8; test_set_bit(&cpu, .Clear, .Decimal, 2); } test "run CLI" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x58; test_set_bit(&cpu, .Clear, .Interrupt, 2); } test "run CLV" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xB8; test_set_bit(&cpu, .Clear, .Overflow, 2); } test "run SEC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x38; test_set_bit(&cpu, .Set, .Carry, 2); } test "run SED" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xF8; test_set_bit(&cpu, .Set, .Decimal, 2); } test "run SEI" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x78; test_set_bit(&cpu, .Set, .Interrupt, 2); } // ASL tests test "run ASL_ACC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x0A; test_displace_bit(&cpu, .ShiftLeft, CPU.A, 0, 2); } test "run ASL_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x06; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .ShiftLeft, 0, 0x11, 5); } test "run ASL_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x16; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .ShiftLeft, 0, 0x11 + 7, 6); } test "run ASL_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x0E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .ShiftLeft, 0, 0x8311, 6); } test "run ASL_ABSX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x1E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .ShiftLeft, 0, 0x8311 + 7, 7); } // LSR tests test "run LSR_ACC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x4A; test_displace_bit(&cpu, .ShiftRight, CPU.A, 0, 2); } test "run LSR_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x46; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .ShiftRight, 0, 0x11, 5); } test "run LSR_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x56; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .ShiftRight, 0, 0x11 + 7, 6); } test "run LSR_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x4E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .ShiftRight, 0, 0x8311, 6); } test "run LSR_ABSX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x5E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .ShiftRight, 0, 0x8311 + 7, 7); } // ROL tests test "run ROL_ACC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x2A; test_displace_bit(&cpu, .RotateLeft, CPU.A, 0, 2); } test "run ROL_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x26; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .RotateLeft, 0, 0x11, 5); } test "run ROL_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x36; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .RotateLeft, 0, 0x11 + 7, 6); } test "run ROL_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x2E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .RotateLeft, 0, 0x8311, 6); } test "run ROL_ABSX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x3E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .RotateLeft, 0, 0x8311 + 7, 7); } // ROR tests test "run ROR_ACC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x6A; test_displace_bit(&cpu, .RotateRight, CPU.A, 0, 2); } test "run ROR_ZP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x66; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .RotateRight, 0, 0x11, 5); } test "run ROR_ZPX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x76; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; test_displace_bit(&cpu, .RotateRight, 0, 0x11 + 7, 6); } test "run ROR_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x6E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .RotateRight, 0, 0x8311, 6); } test "run ROR_ABSX" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.regs[CPU.X] = 7; cpu.memory.data[TEST_ADDRESS + 0] = 0x7E; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_displace_bit(&cpu, .RotateRight, 0, 0x8311 + 7, 7); } // Bit set / clear tests test "run BCC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x90; test_branch_bit(&cpu, .Carry, .Clear, 2); } test "run BCS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xB0; test_branch_bit(&cpu, .Carry, .Set, 2); } test "run BEQ" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xF0; test_branch_bit(&cpu, .Zero, .Set, 2); } test "run BMI" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x30; test_branch_bit(&cpu, .Negative, .Set, 2); } test "run BNE" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xD0; test_branch_bit(&cpu, .Zero, .Clear, 2); } test "run BPL" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x10; test_branch_bit(&cpu, .Negative, .Clear, 2); } test "run BVC" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x50; test_branch_bit(&cpu, .Overflow, .Clear, 2); } test "run BVS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x70; test_branch_bit(&cpu, .Overflow, .Set, 2); } // JMP tests test "run JMP_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x4C; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_jmp(&cpu, 0x8311, false, 3); } test "run JMP_IND" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x6C; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; cpu.memory.data[0x8311 + 0] = 0x74; cpu.memory.data[0x8311 + 1] = 0x20; test_jmp(&cpu, 0x2074, false, 5); } // JSR tests test "run JSR_ABS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x20; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; test_jmp(&cpu, 0x8311, true, 6); } // RTS tests test "run RTS" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x20; cpu.memory.data[TEST_ADDRESS + 1] = 0x11; cpu.memory.data[TEST_ADDRESS + 2] = 0x83; cpu.memory.data[0x8311] = 0x60; test_rts(&cpu); } // BRK tests test "run BRK" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x00; test_brk(&cpu); } // RTI tests test "run RTI" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0x00; test_rti(&cpu); } // NOP tests test "run NOP" { var cpu = CPU.init(); cpu.reset(TEST_ADDRESS); cpu.memory.data[TEST_ADDRESS + 0] = 0xEA; const used = cpu.run(2); testing.expect(used == 2); }
src/cpu.zig
gpa: *Allocator, manifest_dir: fs.Dir, hash: HashHelper = .{}, const Cache = @This(); const std = @import("std"); const crypto = std.crypto; const fs = std.fs; const assert = std.debug.assert; const testing = std.testing; const mem = std.mem; const fmt = std.fmt; const Allocator = std.mem.Allocator; /// Be sure to call `Manifest.deinit` after successful initialization. pub fn obtain(cache: *const Cache) Manifest { return Manifest{ .cache = cache, .hash = cache.hash, .manifest_file = null, .manifest_dirty = false, .hex_digest = undefined, }; } /// This is 128 bits - Even with 2^54 cache entries, the probably of a collision would be under 10^-6 pub const bin_digest_len = 16; pub const hex_digest_len = bin_digest_len * 2; const manifest_file_size_max = 50 * 1024 * 1024; /// The type used for hashing file contents. Currently, this is SipHash128(1, 3), because it /// provides enough collision resistance for the Manifest use cases, while being one of our /// fastest options right now. pub const Hasher = crypto.auth.siphash.SipHash128(1, 3); /// Initial state, that can be copied. pub const hasher_init: Hasher = Hasher.init(&[_]u8{0} ** Hasher.key_length); pub const File = struct { path: ?[]const u8, max_file_size: ?usize, stat: fs.File.Stat, bin_digest: [bin_digest_len]u8, contents: ?[]const u8, pub fn deinit(self: *File, allocator: *Allocator) void { if (self.path) |owned_slice| { allocator.free(owned_slice); self.path = null; } if (self.contents) |contents| { allocator.free(contents); self.contents = null; } self.* = undefined; } }; pub const HashHelper = struct { hasher: Hasher = hasher_init, /// Record a slice of bytes as an dependency of the process being cached pub fn addBytes(hh: *HashHelper, bytes: []const u8) void { hh.hasher.update(mem.asBytes(&bytes.len)); hh.hasher.update(bytes); } pub fn addOptionalBytes(hh: *HashHelper, optional_bytes: ?[]const u8) void { hh.add(optional_bytes != null); hh.addBytes(optional_bytes orelse return); } pub fn addListOfBytes(hh: *HashHelper, list_of_bytes: []const []const u8) void { hh.add(list_of_bytes.len); for (list_of_bytes) |bytes| hh.addBytes(bytes); } pub fn addStringSet(hh: *HashHelper, hm: std.StringArrayHashMapUnmanaged(void)) void { const entries = hm.items(); hh.add(entries.len); for (entries) |entry| { hh.addBytes(entry.key); } } /// Convert the input value into bytes and record it as a dependency of the process being cached. pub fn add(hh: *HashHelper, x: anytype) void { switch (@TypeOf(x)) { std.builtin.Version => { hh.add(x.major); hh.add(x.minor); hh.add(x.patch); }, std.Target.Os.TaggedVersionRange => { switch (x) { .linux => |linux| { hh.add(linux.range.min); hh.add(linux.range.max); hh.add(linux.glibc); }, .windows => |windows| { hh.add(windows.min); hh.add(windows.max); }, .semver => |semver| { hh.add(semver.min); hh.add(semver.max); }, .none => {}, } }, else => switch (@typeInfo(@TypeOf(x))) { .Bool, .Int, .Enum, .Array => hh.addBytes(mem.asBytes(&x)), else => @compileError("unable to hash type " ++ @typeName(@TypeOf(x))), }, } } pub fn addOptional(hh: *HashHelper, optional: anytype) void { hh.add(optional != null); hh.add(optional orelse return); } /// Returns a hex encoded hash of the inputs, without modifying state. pub fn peek(hh: HashHelper) [hex_digest_len]u8 { var copy = hh; return copy.final(); } pub fn peekBin(hh: HashHelper) [bin_digest_len]u8 { var copy = hh; var bin_digest: [bin_digest_len]u8 = undefined; copy.hasher.final(&bin_digest); return bin_digest; } /// Returns a hex encoded hash of the inputs, mutating the state of the hasher. pub fn final(hh: *HashHelper) [hex_digest_len]u8 { var bin_digest: [bin_digest_len]u8 = undefined; hh.hasher.final(&bin_digest); var out_digest: [hex_digest_len]u8 = undefined; _ = std.fmt.bufPrint(&out_digest, "{x}", .{bin_digest}) catch unreachable; return out_digest; } }; pub const Lock = struct { manifest_file: fs.File, pub fn release(lock: *Lock) void { lock.manifest_file.close(); lock.* = undefined; } }; /// Manifest manages project-local `zig-cache` directories. /// This is not a general-purpose cache. /// It is designed to be fast and simple, not to withstand attacks using specially-crafted input. pub const Manifest = struct { cache: *const Cache, /// Current state for incremental hashing. hash: HashHelper, manifest_file: ?fs.File, manifest_dirty: bool, files: std.ArrayListUnmanaged(File) = .{}, hex_digest: [hex_digest_len]u8, /// Add a file as a dependency of process being cached. When `hit` is /// called, the file's contents will be checked to ensure that it matches /// the contents from previous times. /// /// Max file size will be used to determine the amount of space to the file contents /// are allowed to take up in memory. If max_file_size is null, then the contents /// will not be loaded into memory. /// /// Returns the index of the entry in the `files` array list. You can use it /// to access the contents of the file after calling `hit()` like so: /// /// ``` /// var file_contents = cache_hash.files.items[file_index].contents.?; /// ``` pub fn addFile(self: *Manifest, file_path: []const u8, max_file_size: ?usize) !usize { assert(self.manifest_file == null); try self.files.ensureCapacity(self.cache.gpa, self.files.items.len + 1); const resolved_path = try fs.path.resolve(self.cache.gpa, &[_][]const u8{file_path}); const idx = self.files.items.len; self.files.addOneAssumeCapacity().* = .{ .path = resolved_path, .contents = null, .max_file_size = max_file_size, .stat = undefined, .bin_digest = undefined, }; self.hash.addBytes(resolved_path); return idx; } pub fn addOptionalFile(self: *Manifest, optional_file_path: ?[]const u8) !void { self.hash.add(optional_file_path != null); const file_path = optional_file_path orelse return; _ = try self.addFile(file_path, null); } pub fn addListOfFiles(self: *Manifest, list_of_files: []const []const u8) !void { self.hash.add(list_of_files.len); for (list_of_files) |file_path| { _ = try self.addFile(file_path, null); } } /// Check the cache to see if the input exists in it. If it exists, returns `true`. /// A hex encoding of its hash is available by calling `final`. /// /// This function will also acquire an exclusive lock to the manifest file. This means /// that a process holding a Manifest will block any other process attempting to /// acquire the lock. /// /// The lock on the manifest file is released when `deinit` is called. As another /// option, one may call `toOwnedLock` to obtain a smaller object which can represent /// the lock. `deinit` is safe to call whether or not `toOwnedLock` has been called. pub fn hit(self: *Manifest) !bool { assert(self.manifest_file == null); const ext = ".txt"; var manifest_file_path: [self.hex_digest.len + ext.len]u8 = undefined; var bin_digest: [bin_digest_len]u8 = undefined; self.hash.hasher.final(&bin_digest); _ = std.fmt.bufPrint(&self.hex_digest, "{x}", .{bin_digest}) catch unreachable; self.hash.hasher = hasher_init; self.hash.hasher.update(&bin_digest); mem.copy(u8, &manifest_file_path, &self.hex_digest); manifest_file_path[self.hex_digest.len..][0..ext.len].* = ext.*; if (self.files.items.len != 0) { self.manifest_file = try self.cache.manifest_dir.createFile(&manifest_file_path, .{ .read = true, .truncate = false, .lock = .Exclusive, }); } else { // If there are no file inputs, we check if the manifest file exists instead of // comparing the hashes on the files used for the cached item self.manifest_file = self.cache.manifest_dir.openFile(&manifest_file_path, .{ .read = true, .write = true, .lock = .Exclusive, }) catch |err| switch (err) { error.FileNotFound => { self.manifest_dirty = true; self.manifest_file = try self.cache.manifest_dir.createFile(&manifest_file_path, .{ .read = true, .truncate = false, .lock = .Exclusive, }); return false; }, else => |e| return e, }; } const file_contents = try self.manifest_file.?.inStream().readAllAlloc(self.cache.gpa, manifest_file_size_max); defer self.cache.gpa.free(file_contents); const input_file_count = self.files.items.len; var any_file_changed = false; var line_iter = mem.tokenize(file_contents, "\n"); var idx: usize = 0; while (line_iter.next()) |line| { defer idx += 1; const cache_hash_file = if (idx < input_file_count) &self.files.items[idx] else blk: { const new = try self.files.addOne(self.cache.gpa); new.* = .{ .path = null, .contents = null, .max_file_size = null, .stat = undefined, .bin_digest = undefined, }; break :blk new; }; var iter = mem.tokenize(line, " "); const size = iter.next() orelse return error.InvalidFormat; const inode = iter.next() orelse return error.InvalidFormat; const mtime_nsec_str = iter.next() orelse return error.InvalidFormat; const digest_str = iter.next() orelse return error.InvalidFormat; const file_path = iter.rest(); cache_hash_file.stat.size = fmt.parseInt(u64, size, 10) catch return error.InvalidFormat; cache_hash_file.stat.inode = fmt.parseInt(fs.File.INode, inode, 10) catch return error.InvalidFormat; cache_hash_file.stat.mtime = fmt.parseInt(i64, mtime_nsec_str, 10) catch return error.InvalidFormat; std.fmt.hexToBytes(&cache_hash_file.bin_digest, digest_str) catch return error.InvalidFormat; if (file_path.len == 0) { return error.InvalidFormat; } if (cache_hash_file.path) |p| { if (!mem.eql(u8, file_path, p)) { return error.InvalidFormat; } } if (cache_hash_file.path == null) { cache_hash_file.path = try self.cache.gpa.dupe(u8, file_path); } const this_file = fs.cwd().openFile(cache_hash_file.path.?, .{ .read = true }) catch { return error.CacheUnavailable; }; defer this_file.close(); const actual_stat = try this_file.stat(); const size_match = actual_stat.size == cache_hash_file.stat.size; const mtime_match = actual_stat.mtime == cache_hash_file.stat.mtime; const inode_match = actual_stat.inode == cache_hash_file.stat.inode; if (!size_match or !mtime_match or !inode_match) { self.manifest_dirty = true; cache_hash_file.stat = actual_stat; if (isProblematicTimestamp(cache_hash_file.stat.mtime)) { cache_hash_file.stat.mtime = 0; cache_hash_file.stat.inode = 0; } var actual_digest: [bin_digest_len]u8 = undefined; try hashFile(this_file, &actual_digest); if (!mem.eql(u8, &cache_hash_file.bin_digest, &actual_digest)) { cache_hash_file.bin_digest = actual_digest; // keep going until we have the input file digests any_file_changed = true; } } if (!any_file_changed) { self.hash.hasher.update(&cache_hash_file.bin_digest); } } if (any_file_changed) { // cache miss // keep the manifest file open self.unhit(bin_digest, input_file_count); return false; } if (idx < input_file_count) { self.manifest_dirty = true; while (idx < input_file_count) : (idx += 1) { const ch_file = &self.files.items[idx]; try self.populateFileHash(ch_file); } return false; } return true; } pub fn unhit(self: *Manifest, bin_digest: [bin_digest_len]u8, input_file_count: usize) void { // Reset the hash. self.hash.hasher = hasher_init; self.hash.hasher.update(&bin_digest); // Remove files not in the initial hash. for (self.files.items[input_file_count..]) |*file| { file.deinit(self.cache.gpa); } self.files.shrinkRetainingCapacity(input_file_count); for (self.files.items) |file| { self.hash.hasher.update(&file.bin_digest); } } fn populateFileHash(self: *Manifest, ch_file: *File) !void { const file = try fs.cwd().openFile(ch_file.path.?, .{}); defer file.close(); ch_file.stat = try file.stat(); if (isProblematicTimestamp(ch_file.stat.mtime)) { ch_file.stat.mtime = 0; ch_file.stat.inode = 0; } if (ch_file.max_file_size) |max_file_size| { if (ch_file.stat.size > max_file_size) { return error.FileTooBig; } const contents = try self.cache.gpa.alloc(u8, @intCast(usize, ch_file.stat.size)); errdefer self.cache.gpa.free(contents); // Hash while reading from disk, to keep the contents in the cpu cache while // doing hashing. var hasher = hasher_init; var off: usize = 0; while (true) { // give me everything you've got, captain const bytes_read = try file.read(contents[off..]); if (bytes_read == 0) break; hasher.update(contents[off..][0..bytes_read]); off += bytes_read; } hasher.final(&ch_file.bin_digest); ch_file.contents = contents; } else { try hashFile(file, &ch_file.bin_digest); } self.hash.hasher.update(&ch_file.bin_digest); } /// Add a file as a dependency of process being cached, after the initial hash has been /// calculated. This is useful for processes that don't know the all the files that /// are depended on ahead of time. For example, a source file that can import other files /// will need to be recompiled if the imported file is changed. pub fn addFilePostFetch(self: *Manifest, file_path: []const u8, max_file_size: usize) ![]const u8 { assert(self.manifest_file != null); const resolved_path = try fs.path.resolve(self.cache.gpa, &[_][]const u8{file_path}); errdefer self.cache.gpa.free(resolved_path); const new_ch_file = try self.files.addOne(self.cache.gpa); new_ch_file.* = .{ .path = resolved_path, .max_file_size = max_file_size, .stat = undefined, .bin_digest = undefined, .contents = null, }; errdefer self.files.shrinkRetainingCapacity(self.files.items.len - 1); try self.populateFileHash(new_ch_file); return new_ch_file.contents.?; } /// Add a file as a dependency of process being cached, after the initial hash has been /// calculated. This is useful for processes that don't know the all the files that /// are depended on ahead of time. For example, a source file that can import other files /// will need to be recompiled if the imported file is changed. pub fn addFilePost(self: *Manifest, file_path: []const u8) !void { assert(self.manifest_file != null); const resolved_path = try fs.path.resolve(self.cache.gpa, &[_][]const u8{file_path}); errdefer self.cache.gpa.free(resolved_path); const new_ch_file = try self.files.addOne(self.cache.gpa); new_ch_file.* = .{ .path = resolved_path, .max_file_size = null, .stat = undefined, .bin_digest = undefined, .contents = null, }; errdefer self.files.shrinkRetainingCapacity(self.files.items.len - 1); try self.populateFileHash(new_ch_file); } pub fn addDepFilePost(self: *Manifest, dir: fs.Dir, dep_file_basename: []const u8) !void { assert(self.manifest_file != null); const dep_file_contents = try dir.readFileAlloc(self.cache.gpa, dep_file_basename, manifest_file_size_max); defer self.cache.gpa.free(dep_file_contents); var error_buf = std.ArrayList(u8).init(self.cache.gpa); defer error_buf.deinit(); var it: @import("DepTokenizer.zig") = .{ .bytes = dep_file_contents }; // Skip first token: target. switch (it.next() orelse return) { // Empty dep file OK. .target, .target_must_resolve, .prereq => {}, else => |err| { try err.printError(error_buf.writer()); std.log.err("failed parsing {}: {}", .{ dep_file_basename, error_buf.items }); return error.InvalidDepFile; }, } // Process 0+ preqreqs. // Clang is invoked in single-source mode so we never get more targets. while (true) { switch (it.next() orelse return) { .target, .target_must_resolve => return, .prereq => |bytes| try self.addFilePost(bytes), else => |err| { try err.printError(error_buf.writer()); std.log.err("failed parsing {}: {}", .{ dep_file_basename, error_buf.items }); return error.InvalidDepFile; }, } } } /// Returns a hex encoded hash of the inputs. pub fn final(self: *Manifest) [hex_digest_len]u8 { assert(self.manifest_file != null); // We don't close the manifest file yet, because we want to // keep it locked until the API user is done using it. // We also don't write out the manifest yet, because until // cache_release is called we still might be working on creating // the artifacts to cache. var bin_digest: [bin_digest_len]u8 = undefined; self.hash.hasher.final(&bin_digest); var out_digest: [hex_digest_len]u8 = undefined; _ = std.fmt.bufPrint(&out_digest, "{x}", .{bin_digest}) catch unreachable; return out_digest; } pub fn writeManifest(self: *Manifest) !void { const manifest_file = self.manifest_file.?; if (!self.manifest_dirty) return; var contents = std.ArrayList(u8).init(self.cache.gpa); defer contents.deinit(); const writer = contents.writer(); var encoded_digest: [hex_digest_len]u8 = undefined; for (self.files.items) |file| { _ = std.fmt.bufPrint(&encoded_digest, "{x}", .{file.bin_digest}) catch unreachable; try writer.print("{d} {d} {d} {s} {s}\n", .{ file.stat.size, file.stat.inode, file.stat.mtime, &encoded_digest, file.path, }); } try manifest_file.setEndPos(contents.items.len); try manifest_file.pwriteAll(contents.items, 0); self.manifest_dirty = false; } /// Obtain only the data needed to maintain a lock on the manifest file. /// The `Manifest` remains safe to deinit. /// Don't forget to call `writeManifest` before this! pub fn toOwnedLock(self: *Manifest) Lock { const manifest_file = self.manifest_file.?; self.manifest_file = null; return Lock{ .manifest_file = manifest_file }; } /// Releases the manifest file and frees any memory the Manifest was using. /// `Manifest.hit` must be called first. /// Don't forget to call `writeManifest` before this! pub fn deinit(self: *Manifest) void { if (self.manifest_file) |file| { file.close(); } for (self.files.items) |*file| { file.deinit(self.cache.gpa); } self.files.deinit(self.cache.gpa); } }; /// On operating systems that support symlinks, does a readlink. On other operating systems, /// uses the file contents. Windows supports symlinks but only with elevated privileges, so /// it is treated as not supporting symlinks. pub fn readSmallFile(dir: fs.Dir, sub_path: []const u8, buffer: []u8) ![]u8 { if (std.Target.current.os.tag == .windows) { return dir.readFile(sub_path, buffer); } else { return dir.readLink(sub_path, buffer); } } /// On operating systems that support symlinks, does a symlink. On other operating systems, /// uses the file contents. Windows supports symlinks but only with elevated privileges, so /// it is treated as not supporting symlinks. /// `data` must be a valid UTF-8 encoded file path and 255 bytes or fewer. pub fn writeSmallFile(dir: fs.Dir, sub_path: []const u8, data: []const u8) !void { assert(data.len <= 255); if (std.Target.current.os.tag == .windows) { return dir.writeFile(sub_path, data); } else { return dir.symLink(data, sub_path, .{}); } } fn hashFile(file: fs.File, bin_digest: *[Hasher.mac_length]u8) !void { var buf: [1024]u8 = undefined; var hasher = hasher_init; while (true) { const bytes_read = try file.read(&buf); if (bytes_read == 0) break; hasher.update(buf[0..bytes_read]); } hasher.final(bin_digest); } /// If the wall clock time, rounded to the same precision as the /// mtime, is equal to the mtime, then we cannot rely on this mtime /// yet. We will instead save an mtime value that indicates the hash /// must be unconditionally computed. /// This function recognizes the precision of mtime by looking at trailing /// zero bits of the seconds and nanoseconds. fn isProblematicTimestamp(fs_clock: i128) bool { const wall_clock = std.time.nanoTimestamp(); // We have to break the nanoseconds into seconds and remainder nanoseconds // to detect precision of seconds, because looking at the zero bits in base // 2 would not detect precision of the seconds value. const fs_sec = @intCast(i64, @divFloor(fs_clock, std.time.ns_per_s)); const fs_nsec = @intCast(i64, @mod(fs_clock, std.time.ns_per_s)); var wall_sec = @intCast(i64, @divFloor(wall_clock, std.time.ns_per_s)); var wall_nsec = @intCast(i64, @mod(wall_clock, std.time.ns_per_s)); // First make all the least significant zero bits in the fs_clock, also zero bits in the wall clock. if (fs_nsec == 0) { wall_nsec = 0; if (fs_sec == 0) { wall_sec = 0; } else { wall_sec &= @as(i64, -1) << @intCast(u6, @ctz(i64, fs_sec)); } } else { wall_nsec &= @as(i64, -1) << @intCast(u6, @ctz(i64, fs_nsec)); } return wall_nsec == fs_nsec and wall_sec == fs_sec; } test "cache file and then recall it" { if (std.Target.current.os.tag == .wasi) { // https://github.com/ziglang/zig/issues/5437 return error.SkipZigTest; } const cwd = fs.cwd(); const temp_file = "test.txt"; const temp_manifest_dir = "temp_manifest_dir"; const ts = std.time.nanoTimestamp(); try cwd.writeFile(temp_file, "Hello, world!\n"); while (isProblematicTimestamp(ts)) { std.time.sleep(1); } var digest1: [hex_digest_len]u8 = undefined; var digest2: [hex_digest_len]u8 = undefined; { var cache = Cache{ .gpa = testing.allocator, .manifest_dir = try cwd.makeOpenPath(temp_manifest_dir, .{}), }; defer cache.manifest_dir.close(); { var ch = cache.obtain(); defer ch.deinit(); ch.hash.add(true); ch.hash.add(@as(u16, 1234)); ch.hash.addBytes("1234"); _ = try ch.addFile(temp_file, null); // There should be nothing in the cache testing.expectEqual(false, try ch.hit()); digest1 = ch.final(); try ch.writeManifest(); } { var ch = cache.obtain(); defer ch.deinit(); ch.hash.add(true); ch.hash.add(@as(u16, 1234)); ch.hash.addBytes("1234"); _ = try ch.addFile(temp_file, null); // Cache hit! We just "built" the same file testing.expect(try ch.hit()); digest2 = ch.final(); try ch.writeManifest(); } testing.expectEqual(digest1, digest2); } try cwd.deleteTree(temp_manifest_dir); try cwd.deleteFile(temp_file); } test "give problematic timestamp" { var fs_clock = std.time.nanoTimestamp(); // to make it problematic, we make it only accurate to the second fs_clock = @divTrunc(fs_clock, std.time.ns_per_s); fs_clock *= std.time.ns_per_s; testing.expect(isProblematicTimestamp(fs_clock)); } test "give nonproblematic timestamp" { testing.expect(!isProblematicTimestamp(std.time.nanoTimestamp() - std.time.ns_per_s)); } test "check that changing a file makes cache fail" { if (std.Target.current.os.tag == .wasi) { // https://github.com/ziglang/zig/issues/5437 return error.SkipZigTest; } const cwd = fs.cwd(); const temp_file = "cache_hash_change_file_test.txt"; const temp_manifest_dir = "cache_hash_change_file_manifest_dir"; const original_temp_file_contents = "Hello, world!\n"; const updated_temp_file_contents = "Hello, world; but updated!\n"; try cwd.deleteTree(temp_manifest_dir); try cwd.deleteTree(temp_file); const ts = std.time.nanoTimestamp(); try cwd.writeFile(temp_file, original_temp_file_contents); while (isProblematicTimestamp(ts)) { std.time.sleep(1); } var digest1: [hex_digest_len]u8 = undefined; var digest2: [hex_digest_len]u8 = undefined; { var cache = Cache{ .gpa = testing.allocator, .manifest_dir = try cwd.makeOpenPath(temp_manifest_dir, .{}), }; defer cache.manifest_dir.close(); { var ch = cache.obtain(); defer ch.deinit(); ch.hash.addBytes("1234"); const temp_file_idx = try ch.addFile(temp_file, 100); // There should be nothing in the cache testing.expectEqual(false, try ch.hit()); testing.expect(mem.eql(u8, original_temp_file_contents, ch.files.items[temp_file_idx].contents.?)); digest1 = ch.final(); try ch.writeManifest(); } try cwd.writeFile(temp_file, updated_temp_file_contents); { var ch = cache.obtain(); defer ch.deinit(); ch.hash.addBytes("1234"); const temp_file_idx = try ch.addFile(temp_file, 100); // A file that we depend on has been updated, so the cache should not contain an entry for it testing.expectEqual(false, try ch.hit()); // The cache system does not keep the contents of re-hashed input files. testing.expect(ch.files.items[temp_file_idx].contents == null); digest2 = ch.final(); try ch.writeManifest(); } testing.expect(!mem.eql(u8, digest1[0..], digest2[0..])); } try cwd.deleteTree(temp_manifest_dir); try cwd.deleteTree(temp_file); } test "no file inputs" { if (std.Target.current.os.tag == .wasi) { // https://github.com/ziglang/zig/issues/5437 return error.SkipZigTest; } const cwd = fs.cwd(); const temp_manifest_dir = "no_file_inputs_manifest_dir"; defer cwd.deleteTree(temp_manifest_dir) catch {}; var digest1: [hex_digest_len]u8 = undefined; var digest2: [hex_digest_len]u8 = undefined; var cache = Cache{ .gpa = testing.allocator, .manifest_dir = try cwd.makeOpenPath(temp_manifest_dir, .{}), }; defer cache.manifest_dir.close(); { var ch = cache.obtain(); defer ch.deinit(); ch.hash.addBytes("1234"); // There should be nothing in the cache testing.expectEqual(false, try ch.hit()); digest1 = ch.final(); try ch.writeManifest(); } { var ch = cache.obtain(); defer ch.deinit(); ch.hash.addBytes("1234"); testing.expect(try ch.hit()); digest2 = ch.final(); try ch.writeManifest(); } testing.expectEqual(digest1, digest2); } test "Manifest with files added after initial hash work" { if (std.Target.current.os.tag == .wasi) { // https://github.com/ziglang/zig/issues/5437 return error.SkipZigTest; } const cwd = fs.cwd(); const temp_file1 = "cache_hash_post_file_test1.txt"; const temp_file2 = "cache_hash_post_file_test2.txt"; const temp_manifest_dir = "cache_hash_post_file_manifest_dir"; const ts1 = std.time.nanoTimestamp(); try cwd.writeFile(temp_file1, "Hello, world!\n"); try cwd.writeFile(temp_file2, "Hello world the second!\n"); while (isProblematicTimestamp(ts1)) { std.time.sleep(1); } var digest1: [hex_digest_len]u8 = undefined; var digest2: [hex_digest_len]u8 = undefined; var digest3: [hex_digest_len]u8 = undefined; { var cache = Cache{ .gpa = testing.allocator, .manifest_dir = try cwd.makeOpenPath(temp_manifest_dir, .{}), }; defer cache.manifest_dir.close(); { var ch = cache.obtain(); defer ch.deinit(); ch.hash.addBytes("1234"); _ = try ch.addFile(temp_file1, null); // There should be nothing in the cache testing.expectEqual(false, try ch.hit()); _ = try ch.addFilePost(temp_file2); digest1 = ch.final(); try ch.writeManifest(); } { var ch = cache.obtain(); defer ch.deinit(); ch.hash.addBytes("1234"); _ = try ch.addFile(temp_file1, null); testing.expect(try ch.hit()); digest2 = ch.final(); try ch.writeManifest(); } testing.expect(mem.eql(u8, &digest1, &digest2)); // Modify the file added after initial hash const ts2 = std.time.nanoTimestamp(); try cwd.writeFile(temp_file2, "Hello world the second, updated\n"); while (isProblematicTimestamp(ts2)) { std.time.sleep(1); } { var ch = cache.obtain(); defer ch.deinit(); ch.hash.addBytes("1234"); _ = try ch.addFile(temp_file1, null); // A file that we depend on has been updated, so the cache should not contain an entry for it testing.expectEqual(false, try ch.hit()); _ = try ch.addFilePost(temp_file2); digest3 = ch.final(); try ch.writeManifest(); } testing.expect(!mem.eql(u8, &digest1, &digest3)); } try cwd.deleteTree(temp_manifest_dir); try cwd.deleteFile(temp_file1); try cwd.deleteFile(temp_file2); }
src/Cache.zig
const std = @import("../std.zig"); const assert = std.debug.assert; const expect = std.testing.expect; /// Creates a raw "1.0" mantissa for floating point type T. Used to dedupe f80 logic. fn mantissaOne(comptime T: type) comptime_int { return if (floatMantissaDigits(T) == 64) 1 << 63 else 0; } /// Creates floating point type T from an unbiased exponent and raw mantissa. fn reconstructFloat(comptime T: type, exponent: comptime_int, mantissa: comptime_int) T { const TBits = std.meta.Int(.unsigned, @bitSizeOf(T)); const biased_exponent = @as(TBits, exponent + floatExponentMax(T)); return @bitCast(T, (biased_exponent << floatMantissaBits(T)) | @as(TBits, mantissa)); } /// Returns the number of bits in the exponent of floating point type T. pub fn floatExponentBits(comptime T: type) comptime_int { assert(@typeInfo(T) == .Float); return switch (@typeInfo(T).Float.bits) { 16 => 5, 32 => 8, 64 => 11, 80 => 15, 128 => 15, else => @compileError("unknown floating point type " ++ @typeName(T)), }; } /// Returns the number of bits in the mantissa of floating point type T. pub fn floatMantissaBits(comptime T: type) comptime_int { assert(@typeInfo(T) == .Float); return switch (@typeInfo(T).Float.bits) { 16 => 10, 32 => 23, 64 => 52, 80 => 64, 128 => 112, else => @compileError("unknown floating point type " ++ @typeName(T)), }; } /// Returns the number of binary digits in the mantissa of floating point type T. pub fn floatMantissaDigits(comptime T: type) comptime_int { assert(@typeInfo(T) == .Float); // standard IEEE floats have an implicit 0.m or 1.m integer part // f80 is special and has an explicitly stored bit in the MSB // this function corresponds to `MANT_DIG' constants from C return switch (@typeInfo(T).Float.bits) { 16 => 11, 32 => 24, 64 => 53, 80 => 64, 128 => 113, else => @compileError("unknown floating point type " ++ @typeName(T)), }; } /// Returns the minimum exponent that can represent /// a normalised value in floating point type T. pub fn floatExponentMin(comptime T: type) comptime_int { return -floatExponentMax(T) + 1; } /// Returns the maximum exponent that can represent /// a normalised value in floating point type T. pub fn floatExponentMax(comptime T: type) comptime_int { return (1 << (floatExponentBits(T) - 1)) - 1; } /// Returns the smallest subnormal number representable in floating point type T. pub fn floatTrueMin(comptime T: type) T { return reconstructFloat(T, floatExponentMin(T) - 1, 1); } /// Returns the smallest normal number representable in floating point type T. pub fn floatMin(comptime T: type) T { return reconstructFloat(T, floatExponentMin(T), mantissaOne(T)); } /// Returns the largest normal number representable in floating point type T. pub fn floatMax(comptime T: type) T { const all1s_mantissa = (1 << floatMantissaBits(T)) - 1; return reconstructFloat(T, floatExponentMax(T), all1s_mantissa); } /// Returns the machine epsilon of floating point type T. pub fn floatEps(comptime T: type) T { return reconstructFloat(T, -(floatMantissaDigits(T) - 1), mantissaOne(T)); } test "std.math.float" { inline for ([_]type{ f16, f32, f64, f80, f128, c_longdouble }) |T| { // (1 +) for the sign bit, since it is separate from the other bits const size = 1 + floatExponentBits(T) + floatMantissaBits(T); try expect(@bitSizeOf(T) == size); // for machine epsilon, assert expmin <= -prec <= expmax try expect(floatExponentMin(T) <= -(floatMantissaDigits(T) - 1)); try expect(-(floatMantissaDigits(T) - 1) <= floatExponentMax(T)); } }
lib/std/math/float.zig
const std = @import("std"); usingnamespace @import("common.zig"); const ascii = std.ascii; const math = std.math; const fmt = std.fmt; const mem = std.mem; const Version = std.builtin.Version; const assert = std.debug.assert; pub const StatusEvent = struct { version: Version, code: u16, reason: []const u8, }; pub const PayloadEvent = struct { data: []const u8, final: bool = false, }; pub const Event = union(enum) { status: StatusEvent, header: Header, payload: PayloadEvent, head_done: void, skip: void, end: void, }; // TODO: properly implement chunked encoding // - Chunk Extensions // TODO: Parsing options? // - Accept malformed uri (so that it can be properly handled)? // Supports HTTP/1.0 and HTTP/1.1 pub fn create(buffer: []u8, reader: anytype) ResponseParser(@TypeOf(reader)) { // Any buffer smaller than 16 cannot read the most simple status line (1xx A HTTP/1.1\r\n) assert(buffer.len >= 16); return ResponseParser(@TypeOf(reader)).init(buffer, reader); } pub fn ResponseParser(comptime Reader: type) type { return struct { const Self = @This(); read_buffer: []u8, encoding: TransferEncoding = .unknown, has_chunked_trailer: bool = false, response_version: ?Version = null, read_needed: usize = 0, read_current: usize = 0, reader: Reader, trailer_state: bool = false, state: ParserState = .start_line, done: bool = false, pub fn init(buffer: []u8, reader: Reader) Self { return .{ .read_buffer = buffer, .reader = reader, }; } pub fn reset(self: *Self) void { self.encoding = .unknown; self.response_version = null; self.read_needed = 0; self.read_current = 0; self.state = .start_line; self.done = false; } pub const NextError = error{ StreamTooLong, // std.io.reader.readUntilDelimiterOrEof EndOfStream, InvalidStatusLine, UnsupportedVersion, InvalidHeader, InvalidEncodingHeader, InvalidChunkedPayload, } || VerifyLineEndingError || std.fmt.ParseIntError || Reader.Error; pub fn next(self: *Self) NextError!?Event { if (self.done) return null; switch (self.state) { .start_line => { const line = try verifyLineEnding((try self.reader.readUntilDelimiterOrEof(self.read_buffer, '\n')) orelse return error.EndOfStream); if (line.len == 0) return Event.skip; // RFC 7230 Section 3.5 var line_it = mem.split(line, " "); const http_version_buffer = line_it.next() orelse return error.InvalidStatusLine; const code_buffer = line_it.next() orelse return error.InvalidStatusLine; const reason_buffer = line_it.rest(); var version_it = mem.split(http_version_buffer, "/"); const http = version_it.next() orelse return error.InvalidStatusLine; const version_buffer = version_it.next() orelse return error.InvalidStatusLine; // There should not be anything left if (version_it.index) |_| return error.InvalidStatusLine; if (!mem.eql(u8, http, "HTTP")) return error.InvalidStatusLine; const version = Version.parse(version_buffer) catch return error.InvalidStatusLine; if (!supported_versions.includesVersion(version)) return error.UnsupportedVersion; self.response_version = version; self.state = .header; return Event{ .status = .{ .version = version, .code = try fmt.parseUnsigned(u16, code_buffer, 10), .reason = reason_buffer, }, }; }, .header => { const line = try verifyLineEnding((try self.reader.readUntilDelimiterOrEof(self.read_buffer, '\n')) orelse return error.EndOfStream); if (line.len == 0) { if (self.trailer_state) { self.encoding = .unknown; self.done = true; return Event.end; } else { self.state = .body; return Event.head_done; } } const index_separator = mem.indexOf(u8, line, ":") orelse 0; if (index_separator == 0) return error.InvalidHeader; const name = line[0..index_separator]; const value = mem.trim(u8, line[index_separator + 1 ..], &[_]u8{ ' ', '\t' }); if (ascii.eqlIgnoreCase(name, "content-length")) { if (self.encoding != .unknown) return error.InvalidEncodingHeader; self.encoding = .content_length; self.read_needed = fmt.parseUnsigned(usize, value, 10) catch return error.InvalidEncodingHeader; } else if (ascii.eqlIgnoreCase(name, "transfer-encoding")) { if (self.encoding != .unknown) return error.InvalidEncodingHeader; // We can only decode chunked messages, not compressed messages if (ascii.indexOfIgnoreCase(value, "chunked") orelse 1 == 0) { self.encoding = .chunked; } } else if (ascii.eqlIgnoreCase(name, "trailer")) { // TODO: The TE header also needs to be set to "trailer" to allow trailer fields (according to spec) self.has_chunked_trailer = true; } return Event{ .header = .{ .name = name, .value = value, }, }; }, .body => { switch (self.encoding) { .unknown => { self.done = true; return Event.end; }, .content_length => { const left = math.min(self.read_needed - self.read_current, self.read_buffer.len); const read = try self.reader.read(self.read_buffer[0..left]); self.read_current += read; // Is it even possible for read_current to be > read_needed? if (self.read_current >= self.read_needed) { self.encoding = .unknown; } return Event{ .payload = .{ .data = self.read_buffer[0..read], .final = self.read_current >= self.read_needed, }, }; }, .chunked => { if (self.read_needed == 0) { const line = try verifyLineEnding((try self.reader.readUntilDelimiterOrEof(self.read_buffer, '\n')) orelse return error.EndOfStream); const chunk_len = fmt.parseUnsigned(usize, line, 16) catch return error.InvalidChunkedPayload; if (chunk_len == 0) { if (self.has_chunked_trailer) { self.state = .header; self.trailer_state = true; return Event.skip; } else { self.encoding = .unknown; self.done = true; return Event.end; } } else { self.read_needed = chunk_len; self.read_current = 0; } } const left = math.min(self.read_needed - self.read_current, self.read_buffer.len); const read = try self.reader.read(self.read_buffer[0..left]); self.read_current += read; // Is it even possible for read_current to be > read_needed? if (self.read_current >= self.read_needed) { const empty = try verifyLineEnding((try self.reader.readUntilDelimiterOrEof(self.read_buffer[left..], '\n')) orelse return error.EndOfStream); if (empty.len != 0) return error.InvalidChunkedPayload; self.read_needed = 0; } return Event{ .payload = .{ .data = self.read_buffer[0..read], .final = self.read_needed == 0, }, }; }, } }, } } }; } const testing = std.testing; const io = std.io; fn testNextField(parser: anytype, expected: ?Event) !void { const actual = try parser.next(); testing.expect(reworkedMetaEql(actual, expected)); } test "decodes a simple response" { var read_buffer: [32]u8 = undefined; var response = "HTTP/1.1 404 Not Found\r\nHost: localhost\r\nContent-Length: 4\r\n\r\ngood"; var reader = io.fixedBufferStream(response).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .status = .{ .version = .{ .major = 1, .minor = 1, }, .code = 404, .reason = "Not Found", }, }); try testNextField(&parser, .{ .header = .{ .name = "Host", .value = "localhost", }, }); try testNextField(&parser, .{ .header = .{ .name = "Content-Length", .value = "4", }, }); try testNextField(&parser, Event.head_done); try testNextField(&parser, .{ .payload = .{ .data = "good", .final = true, }, }); try testNextField(&parser, Event.end); try testNextField(&parser, null); } test "decodes a simple chunked response" { var read_buffer: [32]u8 = undefined; var response = "HTTP/1.1 200 Ok\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ngood\r\n0\r\n"; var reader = io.fixedBufferStream(response).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .status = .{ .version = .{ .major = 1, .minor = 1, }, .code = 200, .reason = "Ok", }, }); try testNextField(&parser, .{ .header = .{ .name = "Host", .value = "localhost", }, }); try testNextField(&parser, .{ .header = .{ .name = "Transfer-Encoding", .value = "chunked", }, }); try testNextField(&parser, Event.head_done); try testNextField(&parser, .{ .payload = .{ .data = "good", .final = true, }, }); try testNextField(&parser, Event.end); try testNextField(&parser, null); } test "decodes a simple chunked response with trailer" { var read_buffer: [32]u8 = undefined; var response = "HTTP/1.1 200 Ok\r\nHost: localhost\r\nTrailer: Expires\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ngood\r\n0\r\nExpires: now\r\n\r\n"; var reader = io.fixedBufferStream(response).reader(); var parser = create(&read_buffer, reader); try testNextField(&parser, .{ .status = .{ .version = .{ .major = 1, .minor = 1, }, .code = 200, .reason = "Ok", }, }); try testNextField(&parser, .{ .header = .{ .name = "Host", .value = "localhost", }, }); try testNextField(&parser, .{ .header = .{ .name = "Trailer", .value = "Expires", }, }); try testNextField(&parser, .{ .header = .{ .name = "Transfer-Encoding", .value = "chunked", }, }); try testNextField(&parser, Event.head_done); try testNextField(&parser, .{ .payload = .{ .data = "good", .final = true, }, }); try testNextField(&parser, Event.skip); try testNextField(&parser, .{ .header = .{ .name = "Expires", .value = "now", }, }); try testNextField(&parser, Event.end); try testNextField(&parser, null); } comptime { std.testing.refAllDecls(@This()); }
src/parser/response.zig
const std = @import("std"); const opt = @import("opt.zig"); const warn = std.debug.warn; const Allocator = std.mem.Allocator; const stdout = &std.io.getStdOut().writer(); const rand = std.rand.DefaultPrng; // fast unbiased random numbers const time = std.time; /// Returns shuffled arraylist of []u8's, caller owns memory pub fn shuf(file: std.fs.File, seed: u64) !std.ArrayList([]u8) { var lines = std.ArrayList([]u8).init(std.heap.page_allocator); var line: []u8 = undefined; while (true) { // gross stuff pls pr and make this nice line = file.reader().readUntilDelimiterAlloc(std.heap.page_allocator, '\n', std.math.maxInt(u32)) catch break; try lines.append(line); } var prng = rand.init(seed); prng.random.shuffle([]u8, lines.items[0..]); return lines; } const ShufFlags = enum { Help, Version, }; var flags = [_]opt.Flag(ShufFlags){ .{ .name = ShufFlags.Help, .long = "help", }, .{ .name = ShufFlags.Version, .long = "version", }, }; const PrintOptions = enum { Default, }; pub fn main(args: [][]u8) anyerror!u8 { var it = opt.FlagIterator(ShufFlags).init(flags[0..], args); while (it.next_flag() catch { return 1; }) |flag| { switch (flag.name) { ShufFlags.Help => { warn("{s} [FILE_NAME]\n", .{args[0]}); return 0; }, ShufFlags.Version => { warn("TODO", .{}); return 0; }, } } var input = it.next_arg(); var lines: std.ArrayList([]u8) = undefined; if (input) |name| { const file = std.fs.cwd().openFile(name[0..], std.fs.File.OpenFlags{ .read = true, .write = false }) catch |err| { try stdout.print("Error: cannot open file {s}\n", .{name}); return 1; }; lines = try shuf(file, @intCast(u64, time.milliTimestamp())); file.close(); } else { // stdin lines = try shuf(std.io.getStdIn(), @intCast(u64, time.milliTimestamp())); } for (lines.items) |row| { warn("{s}\n", .{row}); std.heap.page_allocator.free(row); } lines.deinit(); return 0; } test "basic shuffle test" { const file = try std.fs.cwd().createFile("/tmp/testshuff", std.fs.File.CreateFlags{ .read = true }); _ = try file.write( \\2 \\1 \\3 \\4 \\5 ); const expected = [5][1]u8{ [_]u8{'1'}, [_]u8{'2'}, [_]u8{'3'}, [_]u8{'4'}, [_]u8{'5'} }; // seek back to start try file.seekTo(0); var result = try shuf(file, 0); file.close(); var i: u8 = 0; while (i < result.items.len) : (i += 1) { std.debug.assert(std.mem.eql(u8, result.items[i], expected[i][0..])); std.heap.page_allocator.free(result.items[i]); } result.deinit(); }
src/shuf.zig
const std = @import("std"); const builtin = @import("builtin"); const Pkg = std.build.Pkg; const string = []const u8; pub const cache = ".zigmod/deps"; pub fn addAllTo(exe: *std.build.LibExeObjStep) void { checkMinZig(builtin.zig_version, exe); @setEvalBranchQuota(1_000_000); for (packages) |pkg| { exe.addPackage(pkg.pkg.?); } var llc = false; var vcpkg = false; inline for (comptime std.meta.declarations(package_data)) |decl| { const pkg = @as(Package, @field(package_data, decl.name)); inline for (pkg.system_libs) |item| { exe.linkSystemLibrary(item); llc = true; } inline for (pkg.c_include_dirs) |item| { exe.addIncludeDir(@field(dirs, decl.name) ++ "/" ++ item); llc = true; } inline for (pkg.c_source_files) |item| { exe.addCSourceFile(@field(dirs, decl.name) ++ "/" ++ item, pkg.c_source_flags); llc = true; } vcpkg = vcpkg or pkg.vcpkg; } if (llc) exe.linkLibC(); if (builtin.os.tag == .windows and vcpkg) exe.addVcpkgPaths(.static) catch |err| @panic(@errorName(err)); } pub const Package = struct { directory: string, pkg: ?Pkg = null, c_include_dirs: []const string = &.{}, c_source_files: []const string = &.{}, c_source_flags: []const string = &.{}, system_libs: []const string = &.{}, vcpkg: bool = false, }; fn checkMinZig(current: std.SemanticVersion, exe: *std.build.LibExeObjStep) void { const min = std.SemanticVersion.parse("null") catch return; if (current.order(min).compare(.lt)) @panic(exe.builder.fmt("Your Zig version v{} does not meet the minimum build requirement of v{}", .{current, min})); } pub const dirs = struct { pub const _root = ""; pub const _b0ov9fnwyq9x = cache ++ "/../.."; pub const _7zwuaufp9upt = cache ++ "/git/file:///home/minebill/git/ansi-term"; }; pub const package_data = struct { pub const _7zwuaufp9upt = Package{ .directory = dirs._7zwuaufp9upt, .pkg = Pkg{ .name = "ansi-term", .path = .{ .path = dirs._7zwuaufp9upt ++ "/src/main.zig" }, .dependencies = null }, }; pub const _b0ov9fnwyq9x = Package{ .directory = dirs._b0ov9fnwyq9x, .pkg = Pkg{ .name = "readline", .path = .{ .path = dirs._b0ov9fnwyq9x ++ "/src/lib.zig" }, .dependencies = &.{ _7zwuaufp9upt.pkg.? } }, }; pub const _root = Package{ .directory = dirs._root, }; }; pub const packages = &[_]Package{ package_data._b0ov9fnwyq9x, }; pub const pkgs = struct { pub const readline = package_data._b0ov9fnwyq9x; }; pub const imports = struct { };
deps.zig
const std = @import("std"); const os = std.os; const warn = std.debug.warn; const STDIN_NAME = "-"; const BUFFER_SIZE = 4096; const Input = struct { fd: i32, pub fn init(name: []const u8) !Input { var self = Input{ .fd = undefined, }; if (std.mem.eql(u8, name, STDIN_NAME)) { // If the input is standardin, we have to use that. self.fd = os.STDIN_FILENO; } else { // In all normal cases, open the file for reading self.fd = try os.open(name, 0, os.O_RDONLY); } return self; } pub fn close(self: Input) void { // Do not do anything if we were reading standard input if (self.fd == os.STDIN_FILENO) { return; } // Get rid of the file descriptor os.close(self.fd); } pub fn dump(self: Input, buf: []u8) !void { while (os.read(self.fd, buf)) |bytes| { if (bytes == 0) { // Returning zero bytes signals EOF. return; } // Dump bytes to stdout _ = try os.write(os.STDOUT_FILENO, buf[0..bytes]); } else |err| { // Bubble up any bizarre errors while dumping. return err; } } }; fn cat(buf: []u8, fname: []const u8) void { var file = Input.init(fname) catch |err| { warn("failed to open {} for reading: {}\n", .{ fname, err }); return; }; defer file.close(); file.dump(buf) catch |err| { warn("failed to write contents of {}: {}\n", .{ fname, err }); }; } // Cats all args and returns the number of args catted. fn cat_args(allocator: *std.mem.Allocator, buf: []u8) u32 { // Initialize reading the arguments & throw out the first one, // which is the program name. var args = std.process.args(); _ = args.next(allocator); var argc: u32 = 0; // Loop through the arguments, aborting if the option fails while (args.next(allocator) orelse return argc) |arg| { argc += 1; cat(buf, arg); } else |err| { // TODO: How can this ever happen? warn("failed to read arguments: {}\n", .{err}); return argc; } unreachable; // args.next errors to signal end of loop } pub fn main() !void { // One-off allocator from: // https://ziglang.org/documentation/0.5.0/#Choosing-an-Allocator var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; // Construct a buffer for syscall read/writes var buf = try allocator.alloc(u8, BUFFER_SIZE); // Cat the arguments we have var argc = cat_args(allocator, buf); // If there were no arguments, cat stdin if (argc == 0) { cat(buf, STDIN_NAME); } }
src/main.zig
const std = @import("std"); const VgaBuffer = struct { buffer: [*]volatile VgaChar = @intToPtr([*]volatile VgaChar, 0xb8000), color: FullColor = .{ .fg = .White, .bg = .Black }, row: usize = 0, column: usize = 0, const Self = @This(); /// Clear the screen to black. Preserves the current color. pub fn initialize(self: *Self) void { self.column = 0; self.row = 0; var y: usize = 0; while (y < VGA_HEIGHT) : (y += 1) { self.clear_row(y); } } /// Write a string to the VGA buffer using the current color. pub fn write(self: *Self, data: []const u8) void { for (data) |c| { self.putChar(.{ .char = c, .color = self.color }); } } /// Set the color used when writing. pub fn set_color(self: *Self, fg: HalfColor, bg: HalfColor) void { self.color = .{ .fg = fg, .bg = bg }; } /// Write `char` at the specified x and y coordinates in the VGA buffer. fn putCharAt(self: *Self, char: VgaChar, x: usize, y: usize) void { self.buffer[y * VGA_WIDTH + x] = char; } /// Write `char` at the current row and column, and move to the next column. /// If the end of the current row is reached, wrap to the next row. fn putChar(self: *Self, char: VgaChar) void { // TODO: handle newline switch (char.char) { '\n' => self.new_line(), else => { switch (char.char) { 0x20...0x7e => self.putCharAt( char, self.column, self.row, ), // Not printable on VGA (outside of ASCII range, or its a control character). // Print a ■ instead. else => self.putCharAt( .{ .char = 0xfe, .color = char.color }, self.column, self.row, ), } self.column += 1; if (self.column == VGA_WIDTH) { self.new_line(); } }, } } fn new_line(self: *Self) void { self.column = 0; switch (self.row) { VGA_HEIGHT - 1 => self.shift_upwards(), else => self.row += 1, } } /// Move the entire buffer up one row, fn shift_upwards(self: *Self) void { // TODO: Implement some backbuffering to be able to scroll while pagelock is on? // This is blocked by paging/heap implementation. var y: usize = 1; while (y < VGA_HEIGHT) : (y += 1) { var x: usize = 0; while (x < VGA_WIDTH) : (x += 1) { const char = self.buffer[y * VGA_WIDTH + x]; self.putCharAt(char, x, y - 1); } } // Clear the bottom line self.clear_row(y - 1); } fn clear_row(self: *Self, y: usize) void { const clear_color = FullColor{ .fg = .Black, .bg = .Black }; var x: usize = 0; while (x < VGA_WIDTH) : (x += 1) { self.putCharAt(.{ .char = ' ', .color = clear_color }, x, y); } } const Writer = std.io.Writer( *Self, WriterError, writer_write, ); const WriterError = error{}; fn writer_write(self: *Self, data: []const u8) WriterError!usize { self.write(data); // FIXME: this is naive return data.len; } pub fn writer(self: *Self) Writer { return .{ .context = self }; } }; /// Global singleton instance pub var buffer: VgaBuffer = .{}; const VGA_WIDTH = 80; const VGA_HEIGHT = 25; /// Half of a VGA color (either foreground or background). const HalfColor = packed enum(u4) { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGrey = 7, DarkGrey = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, LightBrown = 14, White = 15, }; /// Full VGA color const FullColor = packed struct { fg: HalfColor, bg: HalfColor, }; const VgaChar = packed struct { char: u8, color: FullColor, };
src/vga.zig
const std = @import("std"); const unistd = @cImport(@cInclude("unistd.h")); const OpType = enum { INC, MOVE, LOOP, PRINT, }; const Printer = struct { stdout: std.fs.File.Writer, sum1: i32 = 0, sum2: i32 = 0, quiet: bool, fn init(args: anytype) Printer { return Printer { .stdout = if (!args.quiet) std.io.getStdOut().writer() else undefined, .quiet = args.quiet }; } fn print(self: *Printer, n: i32) void { if (self.quiet) { self.sum1 = @mod(self.sum1 + n, 255); self.sum2 = @mod(self.sum2 + self.sum1, 255); } else { self.stdout.writeByte(@intCast(u8, n)) catch unreachable; } } fn getChecksum(self: *const Printer) i32 { return (self.sum2 << 8) | self.sum1; } }; const Tape = struct { pos: usize = 0, tape: std.ArrayList(i32), fn init(alloc: *std.mem.Allocator) Tape { var self = Tape{ .tape = std.ArrayList(i32).init(alloc) }; self.tape.append(0) catch unreachable; return self; } fn get(self: *const Tape) i32 { return self.tape.items[self.pos]; } fn inc(self: *Tape, x: i32) void { self.tape.items[self.pos] += x; } fn move(self: *Tape, x: i32) void { self.pos += @intCast(usize, x); if (self.pos >= self.tape.items.len) { self.tape.appendNTimes(0, self.tape.items.len * 2) catch unreachable; } } }; const Ops = std.ArrayList(Op); const Op = struct { op: OpType = undefined, val: i32 = 0, loop: Ops = undefined, }; const StrIterator = struct { text: []const u8, pos: usize = 0, fn next(self: *StrIterator) ?u8 { if (self.pos < self.text.len) { const res = self.text[self.pos]; self.pos += 1; return res; } return null; } }; const Program = struct { ops: Ops, p: *Printer, a: *std.mem.Allocator, fn init(alloc: *std.mem.Allocator, code: []const u8, printer: *Printer) Program { return Program{ .ops = parse(alloc, &StrIterator{ .text = code }), .p = printer, .a = alloc, }; } fn run(self: *const Program) void { var tape = Tape.init(self.a); self._run(&self.ops, &tape); } fn parse(alloc: *std.mem.Allocator, iter: *StrIterator) Ops { var res: Ops = Ops.init(alloc); while (iter.next()) |value| { switch (value) { '+' => res.append(Op{.op = OpType.INC, .val = 1,}) catch unreachable, '-' => res.append(Op{.op = OpType.INC, .val = -1,}) catch unreachable, '>' => res.append(Op{.op = OpType.MOVE, .val = 1,}) catch unreachable, '<' => res.append(Op{.op = OpType.MOVE, .val = -1,}) catch unreachable, '.' => res.append(Op{.op = OpType.PRINT,}) catch unreachable, '[' => res.append(Op{.op = OpType.LOOP, .loop = parse(alloc, iter)}) catch unreachable, ']' => return res, else => continue, } } return res; } fn _run(self: *const Program, program: *const Ops, tape: *Tape) void { for (program.items) |*op| { switch (op.op) { OpType.INC => tape.inc(op.val), OpType.MOVE => tape.move(op.val), OpType.LOOP => while (tape.get() > 0) self._run(&op.loop, tape), OpType.PRINT => self.p.print(tape.get()), } } } }; fn notify(msg: []const u8) void { const addr = std.net.Address.parseIp("127.0.0.1", 9001) catch unreachable; if (std.net.tcpConnectToAddress(addr)) |stream| { defer stream.close(); _ = stream.write(msg) catch unreachable; } else |_| {} } fn readFile(alloc: *std.mem.Allocator, filename: []const u8) ![]const u8 { const file = try std.fs.cwd().openFile(filename, std.fs.File.OpenFlags{}); defer file.close(); const size = try file.getEndPos(); const text = try alloc.alloc(u8, size); _ = try file.readAll(text); return text; } fn verify(alloc: *std.mem.Allocator) void { const text = \\++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.> \\---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. ; var p_left = Printer.init(.{.quiet = true}); Program.init(alloc, text, &p_left).run(); const left = p_left.getChecksum(); var p_right = Printer.init(.{.quiet = true}); for ("Hello World!\n") |c| { p_right.print(c); } const right = p_right.getChecksum(); if (left != right) { std.debug.panic("{} != {}", .{ left, right }); } } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); var alloc: *std.mem.Allocator = &arena.allocator; verify(alloc); var p = Printer.init(.{.quiet = std.os.getenv("QUIET") != null}); var arg_iter = std.process.args(); _ = arg_iter.skip(); // Skip binary name const name = try arg_iter.next(alloc) orelse { std.debug.panic("Expected argument\n", .{}); }; const text = try readFile(alloc, name); const pid = unistd.getpid(); const pid_str = try std.fmt.allocPrint(alloc, "Zig\t{d}", .{pid}); notify(pid_str); Program.init(alloc, text, &p).run(); notify("stop"); if (p.quiet) { std.debug.print("Output checksum: {}\n", .{p.getChecksum()}); } }
brainfuck/bf.zig
const std = @import("std"); const io = std.io; const File = std.os.File; const assert = std.debug.assert; /// Test if two slices are equal. If not print the contents of the /// expected and actual strings to out_stream and return false. pub fn testExpectedStream(comptime Error: type, out_stream: *io.OutStream(Error), expected: []const u8, actual: []const u8) bool { if (std.mem.eql(u8, expected, actual)) return true; out_stream.print("\n====== expected this output: =========\n") catch {}; out_stream.print("{}", expected) catch {}; out_stream.print("\n======== instead found this: =========\n") catch {}; out_stream.print("{}", actual) catch {}; out_stream.print("\n======================================\n") catch {}; return false; } /// Test if two slices are equal. If not print the contents of the /// expected and actual strings to stderr and return false. pub fn testExpected(expected: []const u8, actual: []const u8) bool { var st = std.debug.getStderrStream() catch return false; return testExpectedStream(std.os.File.WriteError, st, expected, actual); } test "testExpectedError.BufferOutStream" { var bytes: [256]u8 = undefined; var allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; var buffer = try std.Buffer.initSize(allocator, 0); var buf_stream = &std.io.BufferOutStream.init(&buffer).stream; assert(!testExpectedStream(std.io.BufferOutStream.Error, buf_stream, "abd", "abc")); assert(std.mem.eql(u8, buffer.toSlice(), \\ \\====== expected this output: ========= \\abd \\======== instead found this: ========= \\abc \\====================================== \\ ) ); } test "testExpectedError.SliceOutStream" { var bytes: [256]u8 = undefined; var slice_stream = &std.io.SliceOutStream.init(bytes[0..]); var stream = &slice_stream.stream; assert(!testExpectedStream(std.io.SliceOutStream.Error, stream, "abd", "abc")); assert(std.mem.eql(u8, slice_stream.getWritten(), \\ \\====== expected this output: ========= \\abd \\======== instead found this: ========= \\abc \\====================================== \\ ) ); } test "testExpected" { assert(testExpected("abc", "abc")); }
src/testexpected.zig
const os = @import("root").os; const std = @import("std"); const gdt = @import("gdt.zig"); const regs = @import("regs.zig"); const interrupts = @import("interrupts.zig"); const Tss = @import("tss.zig").Tss; pub const sched_stack_size = 0x10000; pub const int_stack_size = 0x10000; pub const task_stack_size = 0x10000; pub const stack_guard_size = 0x1000; pub var bsp_task: os.thread.Task = .{}; pub const kernel_gs_base = regs.MSR(u64, 0xC0000102); pub const TaskData = struct { tss: *Tss = undefined, pub fn load_state(self: *@This()) void { const cpu = os.platform.thread.get_current_cpu(); self.tss.set_interrupt_stack(cpu.int_stack); self.tss.set_scheduler_stack(cpu.sched_stack); cpu.platform_data.gdt.update_tss(self.tss); } }; pub const CoreData = struct { gdt: gdt.Gdt = .{}, rsp_stash: u64 = undefined, // Stash for rsp after syscall instruction lapic: ?os.platform.phys_ptr(*volatile [0x100]u32) = undefined, }; pub const CoreDoorbell = struct { addr: *usize = undefined, pub fn init(self: *@This()) void { const nonbacked = os.memory.vmm.nonbacked(); const virt = @ptrToInt(os.vital(nonbacked.allocFn(nonbacked, 4096, 1, 1, 0), "CoreDoorbell nonbacked").ptr); os.vital(os.memory.paging.map(.{ .virt = virt, .size = 4096, .perm = os.memory.paging.rw(), .memtype = .MemoryWriteBack }), "CoreDoorbell map"); self.addr = @intToPtr(*usize, virt); } pub fn ring(self: *@This()) void { @atomicStore(usize, self.addr, 0, .Release); } pub fn start_monitoring(self: *@This()) void { //asm volatile( // "monitor" // : // : [_]"{rax}"(@ptrToInt(self.addr)), // [_]"{ecx}"(@as(u32, 0)), // [_]"{edx}"(@as(u32, 0)), //); } pub fn wait(self: *@This()) void { //asm volatile( // \\sti // \\mwait // \\cli // : // : [_]"{eax}"(@as(u32, 0)), // [_]"{ecx}"(@as(u32, 0)) //); asm volatile("sti; nop; pause; cli"); } }; const ephemeral = os.memory.vmm.backed(.Ephemeral); pub fn init_task_call(new_task: *os.thread.Task, entry: *os.thread.NewTaskEntry) !void { const cpu = os.platform.thread.get_current_cpu(); new_task.registers.eflags = regs.eflags(); new_task.registers.rdi = @ptrToInt(entry); new_task.registers.rsp = os.lib.libalign.align_down(usize, 16, @ptrToInt(entry)); new_task.registers.cs = gdt.selector.code64; new_task.registers.ss = gdt.selector.data64; new_task.registers.es = gdt.selector.data64; new_task.registers.ds = gdt.selector.data64; new_task.registers.rip = @ptrToInt(entry.function); const tss = try os.memory.vmm.backed(.Ephemeral).create(Tss); tss.* = .{}; new_task.platform_data.tss = tss; tss.set_syscall_stack(new_task.stack); } pub fn yield() void { asm volatile( \\int %[wait_yield_vector] \\ : : [wait_yield_vector] "i" (interrupts.wait_yield_vector) ); } pub fn set_current_cpu(cpu_ptr: *os.platform.smp.CoreData) void { kernel_gs_base.write(@ptrToInt(cpu_ptr)); } pub fn get_current_cpu() *os.platform.smp.CoreData { return @intToPtr(*os.platform.smp.CoreData, kernel_gs_base.read()); } pub fn self_exited() ?*os.thread.Task { const curr = os.platform.get_current_task(); if(curr == &bsp_task) return null; return curr; }
src/platform/x86_64/thread.zig
const qnan128 = @bitCast(f128, @as(u128, 0x7fff800000000000) << 64); const inf128 = @bitCast(f128, @as(u128, 0x7fff000000000000) << 64); const __addtf3 = @import("addXf3.zig").__addtf3; fn test__addtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) void { const x = __addtf3(a, b); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expected_hi and lo == expected_lo) { return; } // test other possible NaN representation (signal NaN) else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } @panic("__addtf3 test failure"); } test "addtf3" { if (@import("std").Target.current.os.tag == .windows) { // TODO https://github.com/ziglang/zig/issues/508 return error.SkipZigTest; } test__addtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // NaN + any = NaN test__addtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // inf + inf = inf test__addtf3(inf128, inf128, 0x7fff000000000000, 0x0); // inf + any = inf test__addtf3(inf128, 0x1.2335653452436234723489432abcdefp+5, 0x7fff000000000000, 0x0); // any + any test__addtf3(0x1.23456734245345543849abcdefp+5, 0x1.edcba52449872455634654321fp-1, 0x40042afc95c8b579, 0x61e58dd6c51eb77c); } const __subtf3 = @import("addXf3.zig").__subtf3; fn test__subtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) void { const x = __subtf3(a, b); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expected_hi and lo == expected_lo) { return; } // test other possible NaN representation (signal NaN) else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } @panic("__subtf3 test failure"); } test "subtf3" { if (@import("std").Target.current.os.tag == .windows) { // TODO https://github.com/ziglang/zig/issues/508 return error.SkipZigTest; } // qNaN - any = qNaN test__subtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // NaN + any = NaN test__subtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // inf - any = inf test__subtf3(inf128, 0x1.23456789abcdefp+5, 0x7fff000000000000, 0x0); // any + any test__subtf3(0x1.234567829a3bcdef5678ade36734p+5, 0x1.ee9d7c52354a6936ab8d7654321fp-1, 0x40041b8af1915166, 0xa44a7bca780a166c); }
lib/std/special/compiler_rt/addXf3_test.zig
const builtin = @import("builtin"); const std = @import("std"); const c = @import("c.zig"); const math = std.math; const comptimePrint = std.fmt.comptimePrint; const window_name = "quaternion julia sets"; const real_time = true; const fps = 24; const window_width = if (real_time) 1280 else 1920; const window_height = if (real_time) 720 else 1080; var oglppo: c.GLuint = 0; // zig fmt: off const cs_image_a = struct { var name_z2: c.GLuint = 0; var name_z3: c.GLuint = 0; var name_z2_cut: c.GLuint = 0; var name_z3_cut: c.GLuint = 0; const group_size_x = 8; const group_size_y = 8; const frame_loc = 0; const time_loc = 1; const resolution_loc = 2; const fractal_c_loc = 3; const beat_loc = 4; const image_unit = 0; const src = " layout(" ++ " local_size_x = " ++ comptimePrint("{d}", .{group_size_x}) ++ ", " ++ " local_size_y = " ++ comptimePrint("{d}", .{group_size_y}) ++ ") in;\n" ++ " layout(location = " ++ comptimePrint("{d}", .{frame_loc}) ++ ") uniform int u_frame;\n" ++ " layout(location = " ++ comptimePrint("{d}", .{time_loc}) ++ ") uniform float u_time;\n" ++ " layout(location = " ++ comptimePrint("{d}", .{beat_loc}) ++ ") uniform float u_beat;\n" ++ " layout(location = " ++ comptimePrint("{d}", .{resolution_loc}) ++ ") uniform vec2 u_resolution;\n" ++ " layout(location = " ++ comptimePrint("{d}", .{fractal_c_loc}) ++ ") uniform vec4 u_fractal_c;\n" ++ " layout(rgba32f, binding = " ++ comptimePrint("{d}", .{image_unit}) ++ ") uniform image2D u_image;\n" ++ \\ \\ //#define Z3 \\ //#define CUT \\ \\ const float k_foc_len = 3.2; \\ const float k_bounding_sphere_rad = 2.2; \\ const int k_num_iter = 200; ++ blk: { break :blk "\n" ++ if (real_time) " const int k_num_bounces = 2;\n const float k_precis = 0.00025;\n\n" else " const int k_num_bounces = 4;\n const float k_precis = 0.00025;\n\n"; } ++ \\ int seed = 1; \\ void srand(int s) { \\ seed = s; \\ } \\ int rand() { \\ seed = seed * 0x343fd + 0x269ec3; \\ return (seed >> 16) & 32767; \\ } \\ float frand() { \\ return float(rand()) / 32767.0; \\ } \\ \\ int hash(int n) { \\ n = (n << 13) ^ n; \\ return n * (n * n * 15731 + 789221) + 1376312589; \\ } \\ \\ vec4 qSquare(vec4 q) { \\ return vec4( \\ q.x * q.x - q.y * q.y - q.z * q.z - q.w * q.w, \\ 2.0 * q.x * q.yzw); \\ } \\ vec4 qCube(vec4 q) { \\ vec4 q2 = q * q; \\ return vec4( \\ q.x * (q2.x - 3.0 * q2.y - 3.0 * q2.z - 3.0 * q2.w), \\ q.yzw * (3.0 * q2.x - q2.y - q2.z - q2.w)); \\ } \\ vec4 qMul(vec4 q0, vec4 q1) { \\ return vec4( \\ q0.x * q1.x - q0.y * q1.y - q0.z * q1.z - q0.w * q1.w, \\ q0.y * q1.x + q0.x * q1.y + q0.z * q1.w - q0.w * q1.z, \\ q0.z * q1.x + q0.x * q1.z + q0.w * q1.y - q0.y * q1.w, \\ q0.w * q1.x + q0.x * q1.w + q0.y * q1.z - q0.z * q1.y); \\ } \\ float qLength2(vec4 q) { \\ return dot(q, q); \\ } \\ \\ vec2 intersectSphere(vec3 ro, vec3 rd, float rad) { \\ float b = dot(ro, rd); \\ float c = dot(ro, ro) - rad * rad; \\ float h = b * b - c; \\ if (h < 0.0) return vec2(-1.0); \\ h = sqrt(h); \\ return vec2(-b - h, -b + h); \\ } \\ \\ vec3 calcBounceDirection(vec3 nor) { \\ float u = frand() * 2.0 - 1.0; \\ float a = frand() * 6.28318531; \\ return normalize(nor + vec3(sqrt(1.0 - u * u) * vec2(cos(a), sin(a)), u)); \\ } \\ \\ mat3 setCamera(vec3 ro, vec3 ta, float cr) { \\ vec3 cw = normalize(ta - ro); \\ vec3 cp = vec3(sin(cr), cos(cr), 0.0); \\ vec3 cu = normalize(cross(cw, cp)); \\ vec3 cv = normalize(cross(cu, cw)); \\ return mat3(cu, cv, cw); \\ } \\ \\ vec2 map(vec3 p) { \\ vec4 z = vec4(p, 0.0); \\ float m2 = 0.0; \\ float n = 0.0; \\ float trap_dist = 1e10; \\ \\ #ifdef Z2 // z^2 + c \\ \\ vec4 zp = vec4(1.0, 0.0, 0.0, 0.0); \\ for (int i = 0; i < k_num_iter; ++i) { \\ zp = 2.0 * qMul(z, zp); \\ z = qSquare(z) + u_fractal_c; \\ m2 = qLength2(z); \\ #ifdef CUT \\ trap_dist = min(trap_dist, length(z.z - 0.25) - 0.01); \\ #else \\ trap_dist = min(trap_dist, length(z.xz - vec2(0.45, 0.55)) - 0.1); \\ #endif \\ if (m2 > 256.0) { \\ break; \\ } \\ n += 1.0; \\ } \\ float m = sqrt(m2); \\ float dist = 0.5 * m * log(m) / length(zp); \\ \\ #endif // #ifdef Z2 \\ \\ #ifdef Z3 // z^3 + c \\ \\ float dz2 = 1.0; \\ for (int i = 0; i < k_num_iter; ++i) { \\ dz2 *= 9.0 * qLength2(qSquare(z)); \\ z = qCube(z) + u_fractal_c; \\ m2 = qLength2(z); \\ trap_dist = min(trap_dist, length(z.xz - vec2(0.45, 0.55)) - 0.1); \\ if (m2 > 256.0) { \\ break; \\ } \\ n += 1.0; \\ } \\ float dist = 0.25 * log(m2) * sqrt(m2 / dz2); \\ \\ #endif // #ifdef Z3 \\ \\ dist = min(dist, trap_dist); \\ #ifdef CUT \\ dist = max(dist, p.y); \\ #endif \\ \\ return vec2(dist, n); \\ } \\ \\ vec2 castRay(vec3 ro, vec3 rd) { \\ float tmax = 7.0; \\ float tmin = k_precis; \\ \\ #ifdef CUT \\ { \\ const float k_split = 0.01; \\ float tp_s = (k_split - ro.y) / rd.y; \\ if (tp_s > 0.0) { \\ if (ro.y > k_split) tmin = max(tmin, tp_s); \\ else tmax = min(tmax, tp_s); \\ } \\ } \\ #endif \\ \\ #if 1 \\ { \\ float tp_f = (-0.8 - ro.y) / rd.y; \\ if (tp_f > 0.0) tmax = min(tmax, tp_f); \\ } \\ #endif \\ \\ #if 1 \\ { \\ vec2 bv = intersectSphere(ro, rd, k_bounding_sphere_rad); \\ if (bv.y < 0.0) return vec2(-2.0, 0.0); \\ tmin = max(tmin, bv.x); \\ tmax = min(tmax, bv.y); \\ } \\ #endif \\ \\ vec2 res = vec2(-1.0); \\ float t = tmin; \\ float lt = 0.0; \\ float lh = 0.0; \\ for (int i = 0; i < 1024; ++i) { \\ res = map(ro + rd * t); \\ if (res.x < k_precis) { \\ break; \\ } \\ lt = t; \\ lh = res.x; \\ t += min(res.x, 0.01) * (0.5 + 0.5 * frand()); \\ if (t > tmax) { \\ break; \\ } \\ } \\ if (lt > 0.0001 && res.x < 0.0) t = lt - lh * (t - lt) / (res.x - lh); \\ res.x = (t < tmax) ? t : -1.0; \\ return res; \\ } \\ \\ vec3 calcNormal(vec3 pos) { \\ const vec2 e = vec2(1.0, -1.0) * 0.5773 * k_precis; \\ return normalize( \\ e.xyy * map(pos + e.xyy).x + \\ e.yyx * map(pos + e.yyx).x + \\ e.yxy * map(pos + e.yxy).x + \\ e.xxx * map(pos + e.xxx).x); \\ } \\ \\ vec3 calcSurfaceColor(vec3 pos, vec3 nor, vec2 tn) { \\ vec3 col = 0.5 + 0.5 * cos(log(tn.y) * vec3(1.0) * 0.9); \\ float inside = smoothstep(11.0, 12.0, tn.y); \\ col *= vec3(0.45, 0.42, 0.40) + vec3(u_beat, 0.0, 0.60 + u_beat) * inside; \\ col = mix(col * col * (3.0 - 2.0 * col), col, inside); \\ col = mix(mix(col, vec3(dot(col, vec3(0.3333))), -0.4), col, inside); \\ return clamp(col, 0.0, 1.0); \\ } \\ \\ vec3 render(vec3 ro, vec3 rd) { \\ vec3 color_mask = vec3(1.0); \\ \\ for (int bounce = 0; bounce < k_num_bounces; ++bounce) { \\ vec2 tn = castRay(ro, rd); \\ float t = tn.x; \\ if (t < 0.0) { \\ return bounce > 0 ? color_mask * 1.65 * step(0.0, rd.y) : vec3(clamp(0.2 + 0.21 * rd.y, 0.0, 1.0)); \\ } else { \\ vec3 pos = ro + rd * t; \\ vec3 nor = calcNormal(pos); \\ color_mask *= calcSurfaceColor(pos, nor, tn); \\ rd = calcBounceDirection(nor); \\ ro = pos + nor * k_precis; \\ } \\ } \\ return vec3(0.0); \\ } \\ \\ void main() { \\ ivec2 q = ivec2(gl_GlobalInvocationID); \\ if (q.x >= int(u_resolution.x) || q.y >= int(u_resolution.y)) { \\ return; \\ } \\ srand(hash(q.x + hash(q.y + hash(1117 * u_frame)))); \\ \\ float an = 0.5 + u_time * 0.05; \\ vec3 ro = 2.0 * vec3(sin(an), 0.8, cos(an)); \\ \\ #ifdef CUT \\ vec3 ta = vec3(0.0, -0.3, 0.0); \\ #else \\ vec3 ta = vec3(0.0, -0.1, 0.0); \\ #endif \\ mat3x3 cam = setCamera(ro, ta, 0.0); \\ \\ vec2 fragcoord = q + vec2(frand(), frand()); \\ \\ vec2 p = (2.0 * fragcoord - u_resolution) / u_resolution.y; \\ vec3 rd = normalize(cam * vec3(p, k_foc_len)); \\ \\ vec3 col = render(ro, rd); \\ \\ vec3 old_col = imageLoad(u_image, q).rgb; ++ blk: { break :blk "\n" ++ if (real_time) \\ imageStore(u_image, q, mix(vec4(old_col, 1.0), vec4(col, 1.0), 0.25)); else \\ if (u_frame == 99) { \\ imageStore(u_image, q, vec4(0.01 * (old_col + col), 1.0)); \\ } else if (u_frame == 0) { \\ imageStore(u_image, q, vec4(col, 1.0)); \\ } else { \\ imageStore(u_image, q, vec4(old_col + col, 1.0)); \\ } ; } ++ " }\n" ;}; // zig fmt: on // zig fmt: off const vs_full_tri = struct { var name: c.GLuint = 0; const src = \\ out gl_PerVertex { \\ vec4 gl_Position; \\ }; \\ \\ void main() { \\ const vec2 positions[] = { vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0) }; \\ gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0); \\ } ;}; // zig fmt: on // zig fmt: off const fs_image = struct { var name: c.GLuint = 0; const resolution_loc = 0; const image_unit = 0; const src = " layout(location = " ++ comptimePrint("{d}", .{resolution_loc}) ++ ") uniform vec2 u_resolution;\n" ++ " layout(binding = " ++ comptimePrint("{d}", .{image_unit}) ++ ") uniform sampler2D u_image;\n" ++ \\ \\ layout(location = 0) out vec4 o_color; \\ \\ void main() { \\ vec2 p = vec2(gl_FragCoord) / u_resolution; \\ vec3 col = textureLod(u_image, p, 0.0).rgb; \\ \\ col = pow(col, vec3(0.4545)); \\ col = pow(col, vec3(0.85, 0.97, 1.0)); \\ col = 0.5 * col + 0.5 * col * col * (3.0 - 2.0 * col); \\ \\ o_color = vec4(col, 1.0); \\ } ;}; // zig fmt: on fn createShaderProgram(stype: c.GLenum, glsl: [*c]const u8, defines: [*c]const u8) c.GLuint { const arg = [3][*c]const u8{ "#version 460 core\n", defines, glsl }; const prog = c.glCreateShaderProgramv(stype, 3, &arg[0]); var status: c.GLint = 0; c.glGetProgramiv(prog, c.GL_LINK_STATUS, &status); if (status == c.GL_FALSE) { var log = [_]u8{0} ** 256; c.glGetProgramInfoLog(prog, log.len, null, &log); std.debug.panic("{s}\n", .{log}); } return prog; } fn drawFractal(time: f32, frame_num: u32, fractal_c: [4]f32, image_a: c.GLuint, shader: c.GLuint, beat: f32) void { c.glProgramUniform1i(shader, cs_image_a.frame_loc, @intCast(i32, frame_num)); c.glProgramUniform1f(shader, cs_image_a.time_loc, time); c.glProgramUniform1f(shader, cs_image_a.beat_loc, beat); c.glProgramUniform2f( shader, cs_image_a.resolution_loc, @intToFloat(f32, window_width), @intToFloat(f32, window_height), ); c.glProgramUniform4fv(shader, cs_image_a.fractal_c_loc, 1, &fractal_c); c.glBindImageTexture( cs_image_a.image_unit, image_a, 0, // level c.GL_FALSE, // layered 0, // layer c.GL_READ_WRITE, c.GL_RGBA32F, ); c.glUseProgramStages(oglppo, c.GL_COMPUTE_SHADER_BIT, shader); c.glDispatchCompute( (window_width + cs_image_a.group_size_x - 1) / cs_image_a.group_size_x, (window_height + cs_image_a.group_size_y - 1) / cs_image_a.group_size_y, 1, ); c.glUseProgramStages(oglppo, c.GL_ALL_SHADER_BITS, 0); c.glMemoryBarrier(c.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); c.glProgramUniform2f( fs_image.name, fs_image.resolution_loc, @intToFloat(f32, window_width), @intToFloat(f32, window_height), ); c.glBindTextureUnit(fs_image.image_unit, image_a); c.glUseProgramStages(oglppo, c.GL_VERTEX_SHADER_BIT, vs_full_tri.name); c.glUseProgramStages(oglppo, c.GL_FRAGMENT_SHADER_BIT, fs_image.name); c.glDrawArrays(c.GL_TRIANGLES, 0, 3); c.glUseProgramStages(oglppo, c.GL_ALL_SHADER_BITS, 0); } pub fn main() !void { _ = c.glfwSetErrorCallback(handleGlfwError); if (c.glfwInit() == c.GLFW_FALSE) { std.debug.panic("glfwInit() failed.\n", .{}); } defer c.glfwTerminate(); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 4); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 6); c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE); c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE); if (builtin.mode == .ReleaseFast) { c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, c.GL_FALSE); } else { c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, c.GL_TRUE); } c.glfwWindowHint(c.GLFW_DEPTH_BITS, 24); c.glfwWindowHint(c.GLFW_STENCIL_BITS, 8); c.glfwWindowHint(c.GLFW_RESIZABLE, c.GLFW_FALSE); const window = c.glfwCreateWindow( window_width, window_height, window_name, null, null, ) orelse { std.debug.panic("glfwCreateWindow() failed.\n", .{}); }; defer c.glfwDestroyWindow(window); c.glfwMakeContextCurrent(window); c.glfwSwapInterval(0); c.initOpenGlEntryPoints(); c.glCreateProgramPipelines(1, &oglppo); c.glBindProgramPipeline(oglppo); if (builtin.mode != .ReleaseFast) { c.glEnable(c.GL_DEBUG_OUTPUT); c.glDebugMessageCallback(handleGlError, null); } const file = try std.fs.cwd().openFile("data/out_beat.clip", .{ .read = true }); defer file.close(); const file_reader = file.reader(); var image_a: c.GLuint = 0; c.glCreateTextures(c.GL_TEXTURE_2D, 1, &image_a); c.glTextureStorage2D( image_a, 1, c.GL_RGBA32F, window_width, window_height, ); c.glClearTexImage( image_a, 0, c.GL_RGBA, c.GL_FLOAT, &[_]f32{ 0.0, 0.0, 0.0, 0.0 }, ); defer c.glDeleteTextures(1, &image_a); cs_image_a.name_z2 = createShaderProgram(c.GL_COMPUTE_SHADER, cs_image_a.src, "#define Z2\n"); cs_image_a.name_z3 = createShaderProgram(c.GL_COMPUTE_SHADER, cs_image_a.src, "#define Z3\n"); cs_image_a.name_z2_cut = createShaderProgram(c.GL_COMPUTE_SHADER, cs_image_a.src, "#define Z2\n#define CUT\n"); cs_image_a.name_z3_cut = createShaderProgram(c.GL_COMPUTE_SHADER, cs_image_a.src, "#define Z3\n#define CUT\n"); defer c.glDeleteProgram(cs_image_a.name_z2); defer c.glDeleteProgram(cs_image_a.name_z3); defer c.glDeleteProgram(cs_image_a.name_z2_cut); defer c.glDeleteProgram(cs_image_a.name_z3_cut); vs_full_tri.name = createShaderProgram(c.GL_VERTEX_SHADER, vs_full_tri.src, ""); defer c.glDeleteProgram(vs_full_tri.name); fs_image.name = createShaderProgram(c.GL_FRAGMENT_SHADER, fs_image.src, ""); defer c.glDeleteProgram(fs_image.name); var vao: c.GLuint = 0; c.glCreateVertexArrays(1, &vao); defer c.glDeleteVertexArrays(1, &vao); c.glBindVertexArray(vao); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa.deinit(); std.debug.assert(leaked == false); } var image_data = try std.ArrayList(u8).initCapacity(&gpa.allocator, window_width * window_height * 3); try image_data.resize(window_width * window_height * 3); defer image_data.deinit(); c.stbi_write_png_compression_level = 10; c.stbi_flip_vertically_on_write(1); const Stage = struct { c: [4]f32, comp: u32, sign: f32, shader: c.GLuint, num_frames: u32, }; const stages = [_]Stage{ .{ // 0 .c = .{ 0.01, 0.5, -1.0, 0.0 }, .comp = 2, .sign = 0.033, .shader = cs_image_a.name_z3_cut, .num_frames = 15 * fps, }, .{ // 1 .c = .{ 0.1, -1.0, 0.0, 0.5 }, .comp = 1, .sign = 2.0, .shader = cs_image_a.name_z2, .num_frames = 8 * fps, }, .{ // 2 .c = .{ 0.01, -1.0, 1.0, 0.0 }, .comp = 2, .sign = -5.0, .shader = cs_image_a.name_z2, .num_frames = 15 * fps, }, .{ // 3 .c = .{ 0.01, 0.0, -1.0, 1.0 }, .comp = 3, .sign = -8.0, .shader = cs_image_a.name_z2, .num_frames = 10 * fps, }, .{ // 4 .c = .{ 0.25, 0.5, -1.0, 0.1 }, .comp = 1, .sign = -2.5, .shader = cs_image_a.name_z3, .num_frames = 20 * fps, }, .{ // 5 .c = .{ -0.035, 6.0 / 22.0, 15.0 / 22.0, -6.0 / 22.0 }, .comp = 0, .sign = 0.05, .shader = cs_image_a.name_z2_cut, .num_frames = 15 * fps, }, .{ // 6 .c = .{ 0.0, 6.0 / 22.0, 15.0 / 22.0, -6.0 / 22.0 }, .comp = 0, .sign = 0.5, .shader = cs_image_a.name_z3, .num_frames = 15 * fps, }, .{ // 7 .c = .{ 0.0, 6.0 / 22.0, 15.0 / 22.0, -6.0 / 22.0 }, .comp = 0, .sign = 0.5, .shader = cs_image_a.name_z2, .num_frames = 15 * fps, }, .{ // 8 .c = .{ 0.0, 6.0 / 22.0, 15.0 / 22.0, -6.0 / 22.0 }, .comp = 0, .sign = 0.5, .shader = cs_image_a.name_z2, .num_frames = 15 * fps, }, .{ // 9 .c = .{ 0.0, 6.0 / 22.0, 15.0 / 22.0, -6.0 / 22.0 }, .comp = 0, .sign = 0.5, .shader = cs_image_a.name_z2, .num_frames = 60 * fps, }, .{ // end .c = .{ 20.0, 20.0, 20.0, 20.0 }, .comp = 0, .sign = 0.0, .shader = cs_image_a.name_z2, .num_frames = 5 * fps, }, }; var frame_num: u32 = 0; var stage: u32 = 0; { var i: u32 = 0; while (i < stage) : (i += 1) { frame_num += stages[i].num_frames; } } var fractal_c = [4]f32{ 0.0, 0.0, 0.0, 0.0 }; var fractal_comp: u32 = 0; var fractal_sign: f32 = 1.0; var fractal_shader: c.GLuint = 0; while (c.glfwWindowShouldClose(window) == c.GLFW_FALSE) { const stats = updateFrameStats(window, window_name); const time = @intToFloat(f32, frame_num) * (1.0 / @intToFloat(f32, fps)); var stages_num_frames: u32 = 0; var i: u32 = 0; while (i < stages.len) : (i += 1) { if (frame_num >= stages_num_frames and stage == i) { stage += 1; fractal_c = stages[i].c; fractal_comp = stages[i].comp; fractal_sign = stages[i].sign; fractal_shader = stages[i].shader; } stages_num_frames += stages[i].num_frames; } fractal_c[@intCast(usize, fractal_comp)] += fractal_sign * 0.001; const beat = blk: { var file_buffer = [_]u8{0} ** 32; var buf = (file_reader.readUntilDelimiterOrEof(file_buffer[0..], '\x20') catch unreachable).?; break :blk std.fmt.parseFloat(f32, buf) catch unreachable; }; var fractal_c_final = fractal_c; if (stage == 2) { fractal_c_final[1] = fractal_c[1] + 0.1 * beat; } else if (stage == 3) { fractal_c[1] += 0.025 * beat; fractal_c_final = fractal_c; } else if (stage == 5) { fractal_c_final[2] = fractal_c[2] + 0.05 * beat; } else if (stage == 6) { fractal_c_final[3] = fractal_c[3] + 0.01 * beat; } else if (stage == 7) { fractal_c_final[2] = fractal_c[2] + 0.007 * beat; fractal_c[0] -= 0.007 * beat; fractal_c[1] -= 0.007 * beat; fractal_c[3] -= 0.007 * beat; for (fractal_c) |*fc| { if (fc.* > 1.0) fc.* = -1.0 else if (fc.* < -1.0) fc.* = 1.0; } fractal_c_final[0] = fractal_c[0]; fractal_c_final[1] = fractal_c[1]; fractal_c_final[3] = fractal_c[3]; } else if (stage == 9) { fractal_c_final = [_]f32{ 0.5, 0.1 * beat, 0.2 * beat, 0.3 * beat }; } else if (stage == 10) { fractal_c[0] += beat * 0.021; fractal_c[1] += beat * 0.022; fractal_c[2] += beat * 0.023; fractal_c[3] += beat * 0.024; for (fractal_c) |*fc| { if (fc.* > 1.0) fc.* = -1.0 else if (fc.* < -1.0) fc.* = 1.0; } fractal_c_final = fractal_c; } if (real_time == false) { var image_num: u32 = 0; while (true) { drawFractal(time, image_num, fractal_c_final, image_a, fractal_shader, beat); c.glFinish(); image_num += 1; if (image_num % 100 == 0) { var buffer = [_]u8{0} ** 128; const buffer_slice = buffer[0..]; const image_name = std.fmt.bufPrint( buffer_slice, "frame_{:0>5}.png", .{frame_num}, ) catch unreachable; c.glReadPixels( 0, 0, window_width, window_height, c.GL_RGB, c.GL_UNSIGNED_BYTE, image_data.items.ptr, ); _ = c.stbi_write_png( image_name.ptr, window_width, window_height, 3, image_data.items.ptr, window_width * 3, ); std.debug.print("Frame {:0>5} saved.\n", .{frame_num}); frame_num += 1; image_num = 0; if (frame_num == 4531) { c.glfwSetWindowShouldClose(window, c.GLFW_TRUE); } break; } } } else { drawFractal(time, frame_num, fractal_c_final, image_a, fractal_shader, beat); frame_num += 1; } if (c.glGetError() != c.GL_NO_ERROR) { std.debug.panic("OpenGL error detected.\n", .{}); } c.glfwSwapBuffers(window); c.glfwPollEvents(); } } fn updateFrameStats( window: *c.GLFWwindow, name: [*:0]const u8, ) struct { time: f64, delta_time: f32 } { const state = struct { var timer: std.time.Timer = undefined; var previous_time_ns: u64 = 0; var header_refresh_time_ns: u64 = 0; var frame_count: u64 = ~@as(u64, 0); }; if (state.frame_count == ~@as(u64, 0)) { state.timer = std.time.Timer.start() catch unreachable; state.previous_time_ns = 0; state.header_refresh_time_ns = 0; state.frame_count = 0; } const now_ns = state.timer.read(); const time = @intToFloat(f64, now_ns) / std.time.ns_per_s; const delta_time = @intToFloat(f32, now_ns - state.previous_time_ns) / std.time.ns_per_s; state.previous_time_ns = now_ns; if ((now_ns - state.header_refresh_time_ns) >= std.time.ns_per_s) { const t = @intToFloat(f64, now_ns - state.header_refresh_time_ns) / std.time.ns_per_s; const avg_fps = @intToFloat(f64, state.frame_count) / t; const ms = (1.0 / avg_fps) * 1000.0; var buffer = [_]u8{0} ** 128; const buffer_slice = buffer[0 .. buffer.len - 1]; const header = std.fmt.bufPrint( buffer_slice, "[{d:.1} fps {d:.3} ms | time: {d:.2}] {s}", .{ avg_fps, ms, time, name }, ) catch buffer_slice; _ = c.glfwSetWindowTitle(window, header.ptr); state.header_refresh_time_ns = now_ns; state.frame_count = 0; } state.frame_count += 1; return .{ .time = time, .delta_time = delta_time }; } fn handleGlfwError(err: c_int, description: [*c]const u8) callconv(.C) void { std.debug.panic("GLFW error: {s}\n", .{@as([*:0]const u8, description)}); } fn handleGlError( source: c.GLenum, mtype: c.GLenum, id: c.GLuint, severity: c.GLenum, length: c.GLsizei, message: [*c]const c.GLchar, user_param: ?*const c_void, ) callconv(.C) void { if (message != null) { std.debug.print("{s}\n", .{message}); } }
src/julia.zig
const std = @import("std"); pub const Uri = struct { /// Scheme component of the URI. i.e gemini:// scheme: []const u8, /// Host component, i.e. http://<host> host: []const u8, /// Optional port component, i.e. http://<host>:[port] port: ?u16, /// Path component of the URI, i.e. gemini://<host>[:port][/path] path: ?[]const u8, /// Query component of an URI, i.e. <host>[path]?[query] query: ?[]const u8, /// Fragment identifier component, which allows for indirect identification of /// a secondary resource fragment: ?[]const u8, }; pub const ParseError = error{ /// Gemini URI's have a maximum length of 1024 bytes. UriTooLong, /// Misses the 'gemini://' scheme MissingScheme, /// URI is missing the host component MissingHost, /// The port was included but could not be parsed InvalidPort, /// Expected a specific character, but instead found a different one InvalidCharacter, /// Host contains an IP-literal, but is missing a closing ']' MissingClosingBracket, /// The port number does not fit within the type (u16). Overflow, }; /// Parses a given slice `input` into a Gemini compliant URI. /// Produces a `ParseError` when the given input is invalid. pub fn parse(input: []const u8) ParseError!Uri { if (input.len == 0) return error.MissingScheme; var uri: Uri = .{ .scheme = undefined, .host = undefined, .port = null, .path = null, .query = null, .fragment = null, }; const State = enum { scheme, host, port, path, query, fragment, // when we finished a component, // use this to detect what to parse next. detect_next, }; var state: State = .scheme; var index: usize = 0; while (index < input.len) { const char = input[index]; switch (state) { .scheme => switch (char) { 'a'...'z', 'A'...'Z', '0'...'9', '+', '-', '.' => index += 1, ':' => { uri.scheme = input[0..index]; state = .host; // read until after '://' index += try expectCharacters(input[index..], "://"); }, else => return error.InvalidCharacter, // expected ':' but found a different character }, .host => switch (char) { '[' => { index += 1; const start = index; for (input[index..]) |cur, idx| { if (cur == ']') { uri.host = input[start .. start + idx]; break; } } else return error.MissingClosingBracket; index += uri.host.len + 1; }, else => if (isRegName(char)) { const start = index; while (index < input.len and isRegName(input[index])) { index += 1; } else { uri.host = input[start..index]; } state = .detect_next; } else { state = .detect_next; }, }, .detect_next => switch (char) { ':', '/', '?', '#' => |cur| { index += 1; state = switch (cur) { '/' => .path, '?' => .query, '#' => .fragment, ':' => .port, else => unreachable, }; }, else => return error.InvalidCharacter, }, .port => { const start = index; while (index < input.len and std.ascii.isDigit(input[index])) { index += 1; } else { uri.port = try std.fmt.parseInt(u16, input[start..index], 10); } state = .detect_next; }, .path => { const start = index; const end = if (std.mem.indexOfAnyPos(u8, input, index, "?#")) |pos| blk: { state = switch (input[pos]) { '#' => .fragment, '?' => .query, else => unreachable, }; break :blk pos; } else input.len; uri.path = input[start..end]; index = end; }, .query => { const start = if (char == '?') index + 1 else index; const end = if (std.mem.indexOfScalarPos(u8, input, start, '#')) |frag| blk: { state = .fragment; break :blk frag; } else input.len; uri.query = input[start..end]; index = end; }, .fragment => { const start = if (char == '#') index + 1 else index; uri.fragment = input[start..input.len]; break; }, } } return uri; } /// Reads over the given slice `buffer` until it reaches the given `delimiters` slice. /// Returns the length it read until found. fn expectCharacters(buffer: []const u8, delimiters: []const u8) !usize { if (!std.mem.startsWith(u8, buffer, delimiters)) return error.InvalidCharacter; return delimiters.len; } /// Returns true when Reg-name /// *( unreserved / %<HEX> / sub-delims ) fn isRegName(char: u8) bool { return isUnreserved(char) or char == '%' or isSubDelim(char); } /// Checks if unreserved character /// ALPHA / DIGIT/ [ "-" / "." / "_" / "~" ] fn isUnreserved(char: u8) bool { return std.ascii.isAlpha(char) or std.ascii.isDigit(char) or switch (char) { '-', '.', '_', '~' => true, else => false, }; } /// Returns true when character is a sub-delim character /// !, $, &, \, (, ), *, *, +, ',', = fn isSubDelim(char: u8) bool { return switch (char) { '!', '$', '&', '\'', '(', ')', '*', '+', ',', '=', => true, else => false, }; } /// Returns true when given char is pchar /// unreserved / pct-encoded / sub-delims / ":" / "@" fn isPChar(char: u8) bool { return switch (char) { '%', ':', '@' => true, else => isUnreserved(char) or isSubDelim(char), }; } test "Scheme" { const cases = .{ .{ "https://", "https" }, .{ "gemini://", "gemini" }, .{ "git://", "git" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.scheme); } const error_cases = .{ "htt?s", "gem||", "ha$", }; inline for (error_cases) |case| { try std.testing.expectError(ParseError.InvalidCharacter, parse(case)); } } test "Host" { const cases = .{ .{ "https://exa2ple", "exa2ple" }, .{ "gemini://example.com", "example.com" }, .{ "git://sub.domain.com", "sub.domain.com" }, .{ "https://[2001:db8:0:0:0:0:2:1]", "2001:db8:0:0:0:0:2:1" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.host); } const error_cases = .{ "https://exam|", "gemini://exa\"", "git://sub.example.[om", }; inline for (error_cases) |case| { try std.testing.expectError(ParseError.InvalidCharacter, parse(case)); } } test "Port" { const cases = .{ .{ "gemini://example.com:100", 100 }, .{ "gemini://example.com:8080", 8080 }, .{ "gemini://example.com:8080/", 8080 }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqual(@as(u16, case[1]), uri.port.?); } const error_cases = .{ "https://exammple.com:10a", "https://example.com:[", }; inline for (error_cases) |case| { try std.testing.expectError(error.InvalidCharacter, parse(case)); } } test "Path" { const cases = .{ .{ "gemini://example.com:100/hello", "hello" }, .{ "gemini://example.com/hello/world", "hello/world" }, .{ "gemini://example.com/../hello", "../hello" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.path.?); } } test "Query" { const cases = .{ .{ "gemini://example.com:100/hello?", "" }, .{ "gemini://example.com/?cool=true", "cool=true" }, .{ "gemini://example.com?hello=world", "hello=world" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.query.?); } } test "Fragment" { const cases = .{ .{ "gemini://example.com:100/hello?#hi", "hi" }, .{ "gemini://example.com/#hello", "hello" }, .{ "gemini://example.com#hello-world", "hello-world" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.fragment.?); } }
src/uri.zig
pub const EXT2_FT_UNKNOWN = 0; pub const EXT2_FT_REG_FILE = 1; pub const EXT2_FT_DIR = 2; pub const EXT2_FT_CHRDEV = 3; pub const EXT2_FT_BLKDEV = 4; pub const EXT2_FT_FIFO = 5; pub const EXT2_FT_SOCK = 6; pub const EXT2_FT_SYMLINK = 7; pub const Ext2_DirectoryEntry = extern struct { inode: u32, // 0 == not used record_length: u16, // offset to the next record entry name_length: u8, // can never be move than rec_len - 8 file_type: u8, // File type EXT2_FT_ name: [*]u8, }; pub const EXT2_S_IFSOCK = 0xC000; // socket pub const EXT2_S_IFLNK = 0xA000; // symbolic link pub const EXT2_S_IFREG = 0x8000; // regular file pub const EXT2_S_IFBLK = 0x6000; // block device pub const EXT2_S_IFDIR = 0x4000; // directory pub const EXT2_S_IFCHR = 0x2000; // character device pub const EXT2_S_IFIFO = 0x1000; // fifo pub const Ext2_InodeTableEntry = extern struct { i_mode: u16, i_uid: u16, i_size: u32, i_atime: u32, i_ctime: u32, i_mtime: u32, i_dtime: u32, i_gid: u16, i_links_count: u16, i_blocks: u32, i_flags: u32, i_osd1: u32, i_block: [12]u32, i_block_indirect: u32, i_block_double_indirect: u32, i_block_triple_indirect: u32, i_generation: u32, i_file_acl: u32, i_dir_acl: u32, i_faddr: u32, i_osd2: [12]u8, }; pub const Ext2_BlockGroupDescriptor = extern struct { bg_block_bitmap: u32, bg_inode_bitmap: u32, bg_inode_table: u32, bg_free_blocks_count: u16, bg_free_inodes_count: u16, bg_used_dirs_count: u16, bg_pad: u16, bg_reserved: [12]u8, }; pub const Ext2_SuperBlock = extern struct { s_inodes_count: u32, s_blocks_count: u32, s_r_blocks_count: u32, s_free_blocks_count: u32, s_free_inodes_count: u32, s_first_data_block: u32, s_log_block_size: u32, s_log_frag_size: u32, s_blocks_per_group: u32, s_frags_per_group: u32, s_inodes_per_group: u32, s_mtime: u32, s_wtime: u32, s_mnt_count: u16, s_max_mnt_count: u16, s_magic: u16, //0xEF53 s_state: u16, s_errors: u16, s_minor_rev_level: u16, s_lastchecK: u32, s_checkinterval: u32, s_creator_os: u32, s_rev_level: u32, s_def_resuid: u16, s_def_resgid: u16, pub fn block_group_count(self: *const Ext2_SuperBlock) u32 { return self.s_blocks_count / self.s_blocks_per_group; } pub fn block_group_size(self: *const Ext2_SuperBlock) u32 { return self.s_blocks_per_group * self.block_size(); } pub fn block_size(self: *const Ext2_SuperBlock) u32 { return @intCast(u32, 1024) << @intCast(u4, self.s_log_block_size); } pub fn block_index_for_block_group_descriptor(self: *const Ext2_SuperBlock, block_group_index: u32) u32 { //FIXME +1 is important as the block descriptor - need to explain why // @import("std").log.info("block_index_for_block_group_descriptor:: {} {} {}", .{ // self.s_first_data_block, // self.s_blocks_per_group, // block_group_index, // }); return self.s_first_data_block + (self.s_blocks_per_group * block_group_index) + 1; } pub fn offset_for_block_index(self: *const Ext2_SuperBlock, block_index: u32) u32 { return block_index * self.block_size(); } pub fn inode_at(self: *const Ext2_SuperBlock, parse_source: anytype, inode: u32) !Ext2_InodeTableEntry { // FIXME: Validate some inode_at stuff var block_for_inode = (inode - 1) / self.s_inodes_per_group; var inode_index = (inode - 1) % self.s_inodes_per_group; var block_descriptor = try self.block_descriptor_at(parse_source, block_for_inode); return try self.inode_table_at(parse_source, &block_descriptor, inode_index); } pub fn inode_table_at(self: *const Ext2_SuperBlock, parse_source: anytype, block_descriptor: *const Ext2_BlockGroupDescriptor, inode_index: u32) !Ext2_InodeTableEntry { // FIXME: Verify inode >= 1 OR error // FIXME: Verify inode_index <= self.s_inodes_per_group OR error var inode_position = self.offset_for_block_index(block_descriptor.bg_inode_table) + @sizeOf(Ext2_InodeTableEntry) * inode_index; //FIXME: Improve this, can we write directly into the struct? var inode_table_entry_buf: [@sizeOf(Ext2_InodeTableEntry)]u8 align(@alignOf(Ext2_InodeTableEntry)) = undefined; try parse_source.seekableStream().seekTo(inode_position); try parse_source.reader().readNoEof(&inode_table_entry_buf); var inode_table_entry = @ptrCast(*const Ext2_InodeTableEntry, &inode_table_entry_buf); //FIXME: Pass in an *out* param? return inode_table_entry.*; } //FIXME: Remove parse_source: anytype param pub fn block_descriptor_at(self: *const Ext2_SuperBlock, parse_source: anytype, block_group_index: u32) !Ext2_BlockGroupDescriptor { // @import("std").log.info("block_descriptor_at:: {}", .{block_group_index}); //FIXME: Assert that block_group_index > 0 (as zero is superblock) (TEST) var block_index = self.block_index_for_block_group_descriptor(block_group_index); // @import("std").log.info("block_descriptor_at::block_index {}", .{block_index}); //FIXME: Assert that block_index < self.s_blocks_count (TEST) var block_position = self.offset_for_block_index(block_index); // @import("std").log.info("block_descriptor_at::block_position {}", .{block_position}); //FIXME: Improve this, can we write directly into the struct? var block_group_descriptor_buf: [@sizeOf(Ext2_BlockGroupDescriptor)]u8 align(@alignOf(Ext2_BlockGroupDescriptor)) = undefined; try parse_source.seekableStream().seekTo(block_position); try parse_source.reader().readNoEof(&block_group_descriptor_buf); var block_group_descriptor = @ptrCast(*const Ext2_BlockGroupDescriptor, &block_group_descriptor_buf); //FIXME: Pass in an *out* param? return block_group_descriptor.*; } }; pub fn DirectoryEntryIterator(ParseSource: anytype) type { return struct { parse_source: ParseSource, position: u32, // Position of the next entry in the filesystem current: Ext2_DirectoryEntry = undefined, current_name_pos: u32 = 0, current_name: [255:0]u8 = undefined, super_block: Ext2_SuperBlock, //TODO: Change to a ref // Lazily reads the filename. Laziness achieved by setting the // current_name[0] = 0 to signify the value has not yet been set. pub fn name(self: *@This()) [*:0]u8 { const name_len = self.current.name_length; if (self.current_name[0] == 0 and name_len > 0) { self.parse_source.seekableStream().seekTo(self.current_name_pos) catch { self.current_name[0] = 0; return &self.current_name; }; self.parse_source.reader().readNoEof(self.current_name[0..name_len]) catch { self.current_name[0] = 0; return &self.current_name; }; self.current_name[name_len] = 0; } return &self.current_name; } pub fn file_type(self: *@This()) !u8 { if (self.super_block.s_rev_level > 0) return self.current.file_type; var inode = try self.super_block.inode_at(self.parse_source, self.current.inode); // TODO: Map other types of file if (inode.i_mode & EXT2_S_IFREG != 0) return EXT2_FT_REG_FILE; if (inode.i_mode & EXT2_S_IFDIR != 0) return EXT2_FT_DIR; // @import("std").log.info("Unknown file_type {X}", .{inode.i_mode}); return 0; } pub fn next(self: *@This()) !?*Ext2_DirectoryEntry { // FIXME: Executes with the current values on return.. is this weird? defer self.position += self.current.record_length; // @import("std").log.info("READ ENTRY: {X}", .{self.position}); var directory_entry_buf: [@sizeOf(Ext2_DirectoryEntry)]u8 align(@alignOf(Ext2_DirectoryEntry)) = undefined; try self.parse_source.seekableStream().seekTo(self.position); try self.parse_source.reader().readNoEof(&directory_entry_buf); //FIXME: Too Long (Shouldn't read the name ptr) var directory_entry = @ptrCast(*const Ext2_DirectoryEntry, &directory_entry_buf); // Reset the current name self.current_name[0] = 0; self.current = directory_entry.*; self.current_name_pos = self.position + @offsetOf(Ext2_DirectoryEntry, "name"); // FIXME: Ternery? if (self.current.inode == 0) return null; return &self.current; } }; } pub const FS = struct { //FIXME: Remove parse_source: anytype param pub fn superblock(self: *const FS, parse_source: anytype) !Ext2_SuperBlock { _ = self; //FIXME: Improve this, can we write directly into the struct? var super_block_buf: [@sizeOf(Ext2_SuperBlock)]u8 align(@alignOf(Ext2_SuperBlock)) = undefined; try parse_source.seekableStream().seekTo(1024); try parse_source.reader().readNoEof(&super_block_buf); var super_block = @ptrCast(*const Ext2_SuperBlock, &super_block_buf); //FIXME: Pass in an *out* param? return super_block.*; } pub fn directory_entry_iterator(self: *const FS, parse_source: anytype, inode: *Ext2_InodeTableEntry) !DirectoryEntryIterator(@TypeOf(parse_source)) { var super_block = try self.superblock(parse_source); // FIXME: How to deal with the filename? When to read it and where to place it? file_name(dir_entry)?? var block_idx = inode.i_block[0]; var directory_entry_position = super_block.offset_for_block_index(block_idx); var directory_entry_buf: [@sizeOf(Ext2_DirectoryEntry)]u8 align(@alignOf(Ext2_DirectoryEntry)) = undefined; try parse_source.seekableStream().seekTo(directory_entry_position); try parse_source.reader().readNoEof(&directory_entry_buf); var directory_entry = @ptrCast(*const Ext2_DirectoryEntry, &directory_entry_buf); return DirectoryEntryIterator(@TypeOf(parse_source)){ .parse_source = parse_source, .position = directory_entry_position, .current = directory_entry.*, .super_block = super_block, }; } pub fn mount(parse_source: anytype) !FS { _ = parse_source; return @as(FS, .{}); } };
libs/ext2/ext2.zig
const builtin = @import("builtin"); const std = @import("std"); const assert = std.debug.assert; comptime { // These are implicitly defined when compiling tests. if (!builtin.is_test) { @export("memcpy", memcpy, builtin.GlobalLinkage.Strong); @export("memmove", memmove, builtin.GlobalLinkage.Strong); @export("memset", memset, builtin.GlobalLinkage.Strong); } } inline fn copyBackward(dest: [*]u8, src: [*]const u8, count: usize) [*]u8 { var ri: usize = 0; while (ri < count) : (ri += 1) { const i = count - ri - 1; dest[i] = src[i]; } return dest; } inline fn copyForward(dest: [*]u8, src: [*]const u8, count: usize) [*]u8 { var i: usize = 0; while (i < count) : (i += 1) { dest[i] = src[i]; } return dest; } extern fn memcpy(noalias dest: [*]u8, noalias src: [*]const u8, count: usize) [*]u8 { return @inlineCall(copyForward, dest, src, count); } test "memcpy" { var a = " " ** 3; _ = memcpy(a[0..].ptr, c"abc", 3); assert(std.mem.eql(u8, a[0..3], "abc")); } extern fn memmove(dest: [*]u8, src: [*]const u8, count: usize) [*]u8 { const dest_p = @ptrToInt(dest); const src_p = @ptrToInt(src); if (dest_p == src_p) { return dest; } if (dest_p + count <= src_p or src_p + count <= dest_p) { return memcpy(dest, src, count); } if (dest_p < src_p) { return copyForward(dest, src, count); } else { return copyBackward(dest, src, count); } } test "memmove" { var c = "abcdefg"; _ = memmove(c[0..].ptr, c"def", 3); assert(std.mem.eql(u8, c[0..7], "defdefg")); var a = "abcdefg"; _ = memmove(a[0..].ptr, a[2..].ptr, 3); assert(std.mem.eql(u8, a[0..7], "cdedefg")); var b = "abcdefg"; _ = memmove(b[2..].ptr, b[0..].ptr, 3); assert(std.mem.eql(u8, b[0..7], "ababcfg")); } extern fn memset(dest: [*]u8, ch: c_int, count: usize) [*]u8 { var i: usize = 0; while (i < count) : (i += 1) { dest[i] = @intCast(u8, ch); } return dest; } test "@memset" { var a = " " ** 7; _ = memset(a[0..].ptr, 'z', 7); assert(std.mem.eql(u8, a[0..7], "zzzzzzz")); } export fn memcmp(lhs: [*]const u8, rhs: [*]const u8, count: usize) c_int { var i: usize = 0; while (i < count) : (i += 1) { if (lhs[i] > rhs[i]) { return 1; } else if (lhs[i] < rhs[i]) { return -1; } } return 0; } test "memcmp" { assert(memcmp(c"aaa", c"aaa", 3) == 0); assert(memcmp(c"aab", c"aac", 3) == -1); assert(memcmp(c"aac", c"aab", 3) == 1); } // NOTE: Return code for memchr is actually a non-const void*. export fn memchr(ptr: [*]const u8, ch: c_int, count: usize) ?*const u8 { var i: usize = 0; while (i < count) : (i += 1) { if (ptr[i] == @intCast(u8, ch)) { return &ptr[i]; } } return null; } test "memchr" { const p = c"aaaab"; assert(memchr(p, 'b', 5) == &p[4]); assert(memchr(p, 'a', 5) == &p[0]); assert(memchr(p, 'c', 2) == null); } export fn strcpy(noalias dest: [*]u8, noalias src: [*]const u8) [*]u8 { var i: usize = 0; while (src[i] != 0) : (i += 1) { dest[i] = src[i]; } dest[i] = 0; return dest; } test "strcpy" { var buffer: [8]u8 = undefined; _ = strcpy(buffer[0..].ptr, c"abc"); assert(std.mem.eql(u8, buffer[0..4], "abc\x00")); } export fn strncpy(noalias dest: [*]u8, noalias src: [*]const u8, count: usize) [*]u8 { var i: usize = 0; while (src[i] != 0 and i < count) : (i += 1) { dest[i] = src[i]; } while (i < count) : (i += 1) { dest[i] = 0; } return dest; } test "strncpy" { var buffer: [4]u8 = undefined; _ = strncpy(buffer[0..].ptr, c"abc", 4); assert(std.mem.eql(u8, buffer[0..4], "abc\x00")); _ = strncpy(buffer[0..].ptr, c"abcdef", 4); assert(std.mem.eql(u8, buffer[0..4], "abcd")); } export fn strcat(noalias dest: [*]u8, noalias src: [*]const u8) [*]u8 { var i: usize = 0; while (dest[i] != 0) : (i += 1) {} var j: usize = 0; while (src[j] != 0) : (j += 1) { dest[i + j] = src[j]; } dest[i + j] = 0; return dest; } test "strcat" { var buffer: [8]u8 = undefined; buffer[0] = 'x'; buffer[1] = 0; _ = strcat(buffer[0..].ptr, c"abc"); assert(std.mem.eql(u8, buffer[0..5], "xabc\x00")); } export fn strncat(noalias dest: [*]u8, noalias src: [*]const u8, count: usize) [*]u8 { var i: usize = 0; while (dest[i] != 0) : (i += 1) {} var j: usize = 0; while (src[j] != 0 and j < count) : (j += 1) { dest[i + j] = src[j]; } dest[i + j] = 0; return dest; } test "strncat" { var buffer: [8]u8 = undefined; buffer[0] = 'x'; buffer[1] = 0; _ = strncat(buffer[0..].ptr, c"abc", 2); assert(std.mem.eql(u8, buffer[0..4], "xab\x00")); } export fn strcmp(lhs: [*]const u8, rhs: [*]const u8) c_int { var i: usize = 0; while (lhs[i] != 0 and rhs[i] != 0) : (i += 1) { if (lhs[i] > rhs[i]) { return 1; } else if (lhs[i] < rhs[i]) { return -1; } } if (lhs[i] == 0 and rhs[i] == 0) { return 0; } else if (rhs[i] == 0) { return 1; } else { return -1; } } test "strcmp" { assert(strcmp(c"abc", c"abc") == 0); assert(strcmp(c"aaa", c"cbb") == -1); assert(strcmp(c"cbb", c"aaa") == 1); } export fn strncmp(lhs: [*]const u8, rhs: [*]const u8, count: usize) c_int { var i: usize = 0; while (lhs[i] != 0 and rhs[i] != 0 and i < count) : (i += 1) { if (lhs[i] > rhs[i]) { return 1; } else if (lhs[i] < rhs[i]) { return -1; } } else { return 0; } if (lhs[i] == 0 and rhs[i] == 0) { return 0; } else if (rhs[i] == 0) { return 1; } else { return -1; } } test "strncmp" { assert(strncmp(c"abc", c"abc", 5) == 0); assert(strncmp(c"aaa", c"cbb", 3) == -1); assert(strncmp(c"aab", c"aaa", 2) == 0); } // NOTE: Actually returns a non-const ref export fn strchr(str: [*]const u8, ch: c_int) ?*const u8 { var i: usize = 0; while (str[i] != 0) : (i += 1) { if (str[i] == @intCast(u8, ch)) { return &str[i]; } } if (ch == 0) { return &str[i]; } return null; } test "strchr" { const p = c"aaaab"; assert(strchr(p, 'b') == &p[4]); assert(strchr(p, 'a') == &p[0]); assert(strchr(p, 'c') == null); } // Slow, O(n*m) version export fn strstr(haystack: [*]const u8, needle: [*]const u8) ?*const u8 { const haystack_len = strlen(haystack); const needle_len = strlen(needle); if (needle_len > haystack_len) { return null; } var i: usize = 0; while (i < haystack_len - needle_len + 1) : (i += 1) { var j: usize = 0; while (j < needle_len) : (j += 1) { if (haystack[i + j] != needle[j]) { break; } } else { return &haystack[i]; } } return null; } test "strstr" { const p = c"aabaacaadaaezzzaaf"; assert(strstr(p, c"aab") == &p[0]); assert(strstr(p, c"aac") == &p[3]); assert(strstr(p, c"a") == &p[0]); assert(strstr(p, c"yyy") == null); assert(strstr(p, c"aafe") == null); assert(strstr(p, c"aaaaaaaaaaaaaaaaaaaaaaaaa") == null); } export fn strlen(str: [*]const u8) usize { var i: usize = 0; while (str[i] != 0) : (i += 1) {} return i; } test "strlen" { assert(strlen(c"") == 0); assert(strlen(c"a") == 1); assert(strlen(c"abcdefgh") == 8); } export fn strpbrk(dest: [*]const u8, breakset: [*]const u8) ?*const u8 { var i: usize = 0; while (dest[i] != 0) : (i += 1) { if (strchr(breakset, dest[i]) != null) { return &dest[i]; } } return null; } test "strpbrk" { const p = c"abc,def ghi!"; assert(strpbrk(p, c", !") == &p[3]); assert(strpbrk(p, c"! ,") == &p[3]); assert(strpbrk(p, c"! ") == &p[7]); assert(strpbrk(p, c"z") == null); } export fn strspn(dest: [*]const u8, accept: [*]const u8) usize { var i: usize = 0; while (dest[i] != 0) : (i += 1) { if (strchr(accept, dest[i]) == null) { break; } } return i; } test "strspn" { assert(strspn(c"12abcd", c"123456789") == 2); assert(strspn(c"12abcd", c"abcdefg") == 0); } export fn strcspn(dest: [*]const u8, reject: [*]const u8) usize { var i: usize = 0; while (dest[i] != 0) : (i += 1) { if (strchr(reject, dest[i]) != null) { break; } } return i; } test "strcspn" { assert(strcspn(c"abcd12", c"123456789") == 4); assert(strcspn(c"12abcd", c"abcdefg") == 2); assert(strcspn(c"a12abcd", c"abcdefg") == 0); } // TODO: depend on LC_COLLATE export fn strcoll(lhs: [*]const u8, rhs: [*]const u8) c_int { return strcmp(lhs, rhs); } // NOTE: Returns const char* instead of non-const as declared. export fn strerror(errnum: c_int) [*]const u8 { // TODO: Add conversions for the remaining. return c"Unknown error xxx"; }
src/string.zig
const std = @import("std"); const assert = std.debug.assert; const panic = std.debug.panic; const Texture = @import("Texture.zig"); const zp = @import("../../zplay.zig"); const gl = zp.deps.gl; const Self = @This(); pub const FramebufferError = error{ InvalidTexture, }; /// id of framebuffer id: gl.GLuint = undefined, /// color texture tex: *Texture = undefined, owned: bool = undefined, /// render buffer object, used for depth and stencil rbo1: gl.GLuint = 0, rbo2: gl.GLuint = 0, pub const Option = struct { has_alpha: bool = true, has_depth_stencil: bool = true, separate_depth_stencil: bool = false, }; pub fn init( allocator: std.mem.Allocator, width: u32, height: u32, option: Option, ) Self { var self = Self{ .tex = Texture.init(allocator, .texture_2d), .owned = true, }; gl.genFramebuffers(1, &self.id); gl.bindFramebuffer(gl.GL_FRAMEBUFFER, self.id); defer gl.bindFramebuffer(gl.GL_FRAMEBUFFER, 0); gl.util.checkError(); // attach color texture self.tex.updateImageData( .texture_2d, 0, if (option.has_alpha) .rgba else .rgb, width, height, null, if (option.has_alpha) .rgba else .rgb, u8, null, false, ); self.tex.setFilteringMode(.minifying, .linear); self.tex.setFilteringMode(.magnifying, .linear); gl.framebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.tex.id, 0); gl.util.checkError(); // attach depth/stencil if (option.has_depth_stencil) { self.allocRenderbuffers(option.separate_stecil_depth); } var status = gl.checkFramebufferStatus(gl.GL_FRAMEBUFFER); gl.util.checkError(); if (status != gl.GL_FRAMEBUFFER_COMPLETE) { panic("frame buffer's status is wrong: {x}", .{status}); } return self; } pub fn fromTexture(tex: *Texture, option: Option) !Self { if (tex.tt != .texture_2d or (tex.format != .rgb and tex.format != .rgba)) { return error.InvalidTexture; } var self = Self{ .tex = tex, .owned = false, }; gl.genFramebuffers(1, &self.id); gl.bindFramebuffer(gl.GL_FRAMEBUFFER, self.id); defer gl.bindFramebuffer(gl.GL_FRAMEBUFFER, 0); gl.util.checkError(); // attach color texture gl.framebufferTexture2D( gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.tex.id, 0, ); gl.util.checkError(); // attach depth/stencil if (option.has_depth_stencil) { self.allocDepthStencil(option.separate_depth_stencil); } var status = gl.checkFramebufferStatus(gl.GL_FRAMEBUFFER); gl.util.checkError(); if (status != gl.GL_FRAMEBUFFER_COMPLETE) { panic("frame buffer's status is wrong: {x}", .{status}); } return self; } /// attach depth/stencil buffers fn allocDepthStencil(self: *Self, separate_stecil_depth: bool) void { gl.genRenderbuffers(1, &self.rbo1); defer gl.bindRenderbuffer(gl.GL_RENDERBUFFER, 0); if (separate_stecil_depth) { gl.genRenderbuffers(1, &self.rbo2); // depth gl.bindRenderbuffer(gl.GL_RENDERBUFFER, self.rbo1); gl.renderbufferStorage( gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT, @intCast(c_int, self.tex.width), @intCast(c_int, self.tex.height.?), ); gl.framebufferRenderbuffer( gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, gl.GL_RENDERBUFFER, self.rbo1, ); // stencil gl.bindRenderbuffer(gl.GL_RENDERBUFFER, self.rbo2); gl.renderbufferStorage( gl.GL_RENDERBUFFER, gl.GL_STENCIL_INDEX, @intCast(c_int, self.tex.width), @intCast(c_int, self.tex.height.?), ); gl.framebufferRenderbuffer( gl.GL_FRAMEBUFFER, gl.GL_STENCIL_ATTACHMENT, gl.GL_RENDERBUFFER, self.rbo2, ); } else { gl.bindRenderbuffer(gl.GL_RENDERBUFFER, self.rbo1); gl.renderbufferStorage( gl.GL_RENDERBUFFER, gl.GL_DEPTH24_STENCIL8, @intCast(c_int, self.tex.width), @intCast(c_int, self.tex.height.?), ); gl.framebufferRenderbuffer( gl.GL_FRAMEBUFFER, gl.GL_DEPTH_STENCIL_ATTACHMENT, gl.GL_RENDERBUFFER, self.rbo1, ); } gl.util.checkError(); } pub fn deinit(self: Self) void { if (self.owned) { self.tex.deinit(); } if (self.rbo1 > 0) { gl.deleteRenderbuffers(1, &self.rbo1); } if (self.rbo2 > 0) { gl.deleteRenderbuffers(1, &self.rbo2); } gl.deleteFramebuffers(1, &self.id); gl.util.checkError(); }
src/graphics/common/Framebuffer.zig
const Builder = std.build.Builder; const std = @import("std"); pub fn build(b: *Builder) void { const native_opt = b.option(bool, "native", "if many cpu, turn this on"); const is_native = native_opt orelse true; var target: std.zig.CrossTarget = undefined; if (is_native) { target = b.standardTargetOptions(.{}); } else { // my friends amd cpu is an fx 6300 and it kind of didnt work so target = b.standardTargetOptions(.{ .default_target = .{ .cpu_model = .{ .explicit = &std.Target.x86.cpu.athlon_fx }, }, }); } const mode = b.standardReleaseOptions(); // this exports both a library and a binary // TODO separate exe entrypoint and lib entrypoint const exe = b.addExecutable("zigdig", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); // const exe2 = b.addExecutable("zigdig-async", "src/async_main.zig"); // exe2.setBuildMode(mode); // const exe3 = b.addExecutable("zigdig-stdin", "src/main_stdin.zig"); // exe3.setBuildMode(mode); const lib = b.addStaticLibrary("zigdig", "src/pkg2/dns.zig"); lib.setTarget(target); lib.setBuildMode(mode); var lib_tests = b.addTest("src/pkg2/dns.zig"); lib_tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&lib_tests.step); const run_cmd = exe.run(); const run_step = b.step("run", "Run example binary"); run_step.dependOn(&run_cmd.step); b.default_step.dependOn(&lib.step); b.default_step.dependOn(&exe.step); // b.default_step.dependOn(&exe2.step); // b.default_step.dependOn(&exe3.step); lib.addPackagePath("dns", "src/pkg2/dns.zig"); exe.addPackagePath("dns", "src/pkg2/dns.zig"); // exe2.addPackagePath("dns", "src/pkg/dns.zig"); // exe3.addPackagePath("dns", "src/pkg/dns.zig"); b.installArtifact(lib); b.installArtifact(exe); // b.installArtifact(exe2); // b.installArtifact(exe3); }
build.zig
const std = @import("std"); const qoi = @import("qoi.zig"); const total_rounds = 4096; pub fn main() !void { try perform(true); try perform(false); } fn perform(comptime test_encoder: bool) !void { const allocator = std.heap.c_allocator; const source_data = @embedFile("../data/zero.qoi"); const ref_data = @embedFile("../data/zero.raw"); var progress = std.Progress{}; const benchmark = progress.start("Benchmark", total_rounds); var total_time: u64 = 0; var rounds: usize = total_rounds; while (rounds > 0) { rounds -= 1; var start_point: i128 = undefined; var end_point: i128 = undefined; if (test_encoder) { start_point = std.time.nanoTimestamp(); const memory = try qoi.encodeBuffer(allocator, qoi.ConstImage{ .width = 512, .height = 512, .pixels = std.mem.bytesAsSlice(qoi.Color, ref_data), .colorspace = .sRGB, }); defer allocator.free(memory); end_point = std.time.nanoTimestamp(); if (!std.mem.eql(u8, source_data, memory)) return error.EncodingError; } else { start_point = std.time.nanoTimestamp(); var image = try qoi.decodeBuffer(allocator, source_data); defer image.deinit(allocator); end_point = std.time.nanoTimestamp(); if (image.width != 512 or image.height != 512) return error.DecodingError; if (!std.mem.eql(u8, ref_data, std.mem.sliceAsBytes(image.pixels))) return error.DecodingError; } total_time += @intCast(u64, end_point - start_point); benchmark.completeOne(); } if (test_encoder) { std.debug.print("Encoding time for {} => {} bytes: {}\n", .{ ref_data.len, source_data.len, std.fmt.fmtDuration(total_time / total_rounds), }); } else { std.debug.print("Decoding time for {} => {} bytes: {}\n", .{ source_data.len, ref_data.len, std.fmt.fmtDuration(total_time / total_rounds), }); } }
src/bench.zig
pub const TBS_CONTEXT_VERSION_ONE = @as(u32, 1); pub const TBS_SUCCESS = @as(u32, 0); pub const TBS_OWNERAUTH_TYPE_FULL = @as(u32, 1); pub const TBS_OWNERAUTH_TYPE_ADMIN = @as(u32, 2); pub const TBS_OWNERAUTH_TYPE_USER = @as(u32, 3); pub const TBS_OWNERAUTH_TYPE_ENDORSEMENT = @as(u32, 4); pub const TBS_OWNERAUTH_TYPE_ENDORSEMENT_20 = @as(u32, 12); pub const TBS_OWNERAUTH_TYPE_STORAGE_20 = @as(u32, 13); pub const TBS_CONTEXT_VERSION_TWO = @as(u32, 2); pub const TPM_WNF_INFO_CLEAR_SUCCESSFUL = @as(u32, 1); pub const TPM_WNF_INFO_OWNERSHIP_SUCCESSFUL = @as(u32, 2); pub const TPM_WNF_INFO_NO_REBOOT_REQUIRED = @as(u32, 1); pub const TPM_VERSION_UNKNOWN = @as(u32, 0); pub const TPM_VERSION_12 = @as(u32, 1); pub const TPM_VERSION_20 = @as(u32, 2); pub const TPM_IFTYPE_UNKNOWN = @as(u32, 0); pub const TPM_IFTYPE_1 = @as(u32, 1); pub const TPM_IFTYPE_TRUSTZONE = @as(u32, 2); pub const TPM_IFTYPE_HW = @as(u32, 3); pub const TPM_IFTYPE_EMULATOR = @as(u32, 4); pub const TPM_IFTYPE_SPB = @as(u32, 5); pub const TBS_TCGLOG_SRTM_CURRENT = @as(u32, 0); pub const TBS_TCGLOG_DRTM_CURRENT = @as(u32, 1); pub const TBS_TCGLOG_SRTM_BOOT = @as(u32, 2); pub const TBS_TCGLOG_SRTM_RESUME = @as(u32, 3); pub const TBS_TCGLOG_DRTM_BOOT = @as(u32, 4); pub const TBS_TCGLOG_DRTM_RESUME = @as(u32, 5); //-------------------------------------------------------------------------------- // Section: Types (6) //-------------------------------------------------------------------------------- pub const TBS_COMMAND_PRIORITY = enum(u32) { LOW = 100, NORMAL = 200, SYSTEM = 400, HIGH = 300, MAX = 2147483648, }; pub const TBS_COMMAND_PRIORITY_LOW = TBS_COMMAND_PRIORITY.LOW; pub const TBS_COMMAND_PRIORITY_NORMAL = TBS_COMMAND_PRIORITY.NORMAL; pub const TBS_COMMAND_PRIORITY_SYSTEM = TBS_COMMAND_PRIORITY.SYSTEM; pub const TBS_COMMAND_PRIORITY_HIGH = TBS_COMMAND_PRIORITY.HIGH; pub const TBS_COMMAND_PRIORITY_MAX = TBS_COMMAND_PRIORITY.MAX; pub const TBS_COMMAND_LOCALITY = enum(u32) { ZERO = 0, ONE = 1, TWO = 2, THREE = 3, FOUR = 4, }; pub const TBS_COMMAND_LOCALITY_ZERO = TBS_COMMAND_LOCALITY.ZERO; pub const TBS_COMMAND_LOCALITY_ONE = TBS_COMMAND_LOCALITY.ONE; pub const TBS_COMMAND_LOCALITY_TWO = TBS_COMMAND_LOCALITY.TWO; pub const TBS_COMMAND_LOCALITY_THREE = TBS_COMMAND_LOCALITY.THREE; pub const TBS_COMMAND_LOCALITY_FOUR = TBS_COMMAND_LOCALITY.FOUR; pub const TBS_CONTEXT_PARAMS = extern struct { version: u32, }; pub const TBS_CONTEXT_PARAMS2 = extern struct { version: u32, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, asUINT32: u32, }, }; pub const tdTPM_WNF_PROVISIONING = extern struct { status: u32, message: [28]u8, }; pub const TPM_DEVICE_INFO = extern struct { structVersion: u32, tpmVersion: u32, tpmInterfaceType: u32, tpmImpRevision: u32, }; //-------------------------------------------------------------------------------- // Section: Functions (13) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "tbs" fn Tbsi_Context_Create( pContextParams: ?*TBS_CONTEXT_PARAMS, phContext: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "tbs" fn Tbsip_Context_Close( hContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "tbs" fn Tbsip_Submit_Command( hContext: ?*c_void, Locality: TBS_COMMAND_LOCALITY, Priority: TBS_COMMAND_PRIORITY, // TODO: what to do with BytesParamIndex 4? pabCommand: ?*u8, cbCommand: u32, // TODO: what to do with BytesParamIndex 6? pabResult: ?*u8, pcbResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "tbs" fn Tbsip_Cancel_Commands( hContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "tbs" fn Tbsi_Physical_Presence_Command( hContext: ?*c_void, // TODO: what to do with BytesParamIndex 2? pabInput: ?*u8, cbInput: u32, // TODO: what to do with BytesParamIndex 4? pabOutput: ?*u8, pcbOutput: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "tbs" fn Tbsi_Get_TCG_Log( hContext: ?*c_void, // TODO: what to do with BytesParamIndex 2? pOutputBuf: ?*u8, pOutputBufLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tbs" fn Tbsi_GetDeviceInfo( Size: u32, // TODO: what to do with BytesParamIndex 0? Info: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tbs" fn Tbsi_Get_OwnerAuth( hContext: ?*c_void, ownerauthType: u32, // TODO: what to do with BytesParamIndex 3? pOutputBuf: ?*u8, pOutputBufLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tbs" fn Tbsi_Revoke_Attestation( ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "tbs" fn GetDeviceID( // TODO: what to do with BytesParamIndex 1? pbWindowsAIK: ?*u8, cbWindowsAIK: u32, pcbResult: ?*u32, pfProtectedByTPM: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "tbs" fn GetDeviceIDString( pszWindowsAIK: ?[*:0]u16, cchWindowsAIK: u32, pcchResult: ?*u32, pfProtectedByTPM: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "tbs" fn Tbsi_Create_Windows_Key( keyHandle: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.17134' pub extern "tbs" fn Tbsi_Get_TCG_Log_Ex( logType: u32, // TODO: what to do with BytesParamIndex 2? pbOutput: ?*u8, pcbOutput: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (2) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; const HRESULT = @import("../foundation.zig").HRESULT; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/system/tpm_base_services.zig
const std = @import("std"); const ShaderModule = @This(); /// The type erased pointer to the ShaderModule implementation /// Equal to c.WGPUShaderModule for NativeInstance. ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void, getCompilationInfo: fn (ptr: *anyopaque, callback: *CompilationInfoCallback) void, }; pub inline fn reference(shader: ShaderModule) void { shader.vtable.reference(shader.ptr); } pub inline fn release(shader: ShaderModule) void { shader.vtable.release(shader.ptr); } pub inline fn setLabel(shader: ShaderModule, label: [:0]const u8) void { shader.vtable.setLabel(shader.ptr, label); } pub inline fn getCompilationInfo(shader: ShaderModule, callback: *CompilationInfoCallback) void { shader.vtable.getCompilationInfo(shader.ptr, callback); } pub const CompilationInfoCallback = struct { type_erased_ctx: *anyopaque, type_erased_callback: fn (ctx: *anyopaque, status: CompilationInfoRequestStatus, info: *const CompilationInfo) callconv(.Inline) void, pub fn init( comptime Context: type, ctx: Context, comptime callback: fn (ctx: Context, status: CompilationInfoRequestStatus, info: *const CompilationInfo) void, ) CompilationInfoCallback { const erased = (struct { pub inline fn erased(type_erased_ctx: *anyopaque, status: CompilationInfoRequestStatus) void { callback(if (Context == void) {} else @ptrCast(Context, @alignCast(std.meta.alignment(Context), type_erased_ctx)), status); } }).erased; return .{ .type_erased_ctx = if (Context == void) undefined else ctx, .type_erased_callback = erased, }; } }; pub const CompilationInfoRequestStatus = enum(u32) { success = 0x00000000, err = 0x00000001, device_lost = 0x00000002, unknown = 0x00000003, }; pub const CompilationInfo = struct { messages: []const CompilationMessage, }; pub const CompilationMessageType = enum(u32) { err = 0x00000000, warning = 0x00000001, info = 0x00000002, }; pub const CompilationMessage = extern struct { reserved: ?*anyopaque = null, message: [*:0]const u8, type: CompilationMessageType, line_num: u64, line_pos: u64, offset: u64, length: u64, }; pub const CodeTag = enum { spirv, wgsl, }; pub const Descriptor = struct { label: ?[*:0]const u8 = null, code: union(CodeTag) { wgsl: [*:0]const u8, spirv: []const u32, }, }; test { _ = VTable; _ = reference; _ = release; _ = CompilationInfoRequestStatus; _ = CompilationInfo; _ = CompilationMessageType; _ = CompilationMessage; _ = CodeTag; _ = Descriptor; }
gpu/src/ShaderModule.zig
const std = @import("std"); const builtin = std.builtin; const io = std.io; const meta = std.meta; const trait = std.trait; const DefaultPrng = std.rand.DefaultPrng; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectError = std.testing.expectError; const mem = std.mem; const fs = std.fs; const File = std.fs.File; const tmpDir = std.testing.tmpDir; test "write a file, read it, then delete it" { var tmp = tmpDir(.{}); defer tmp.cleanup(); var data: [1024]u8 = undefined; var prng = DefaultPrng.init(1234); prng.random.bytes(data[0..]); const tmp_file_name = "temp_test_file.txt"; { var file = try tmp.dir.createFile(tmp_file_name, .{}); defer file.close(); var buf_stream = io.bufferedOutStream(file.outStream()); const st = buf_stream.outStream(); try st.print("begin", .{}); try st.writeAll(data[0..]); try st.print("end", .{}); try buf_stream.flush(); } { // Make sure the exclusive flag is honored. expectError(File.OpenError.PathAlreadyExists, tmp.dir.createFile(tmp_file_name, .{ .exclusive = true })); } { var file = try tmp.dir.openFile(tmp_file_name, .{}); defer file.close(); const file_size = try file.getEndPos(); const expected_file_size: u64 = "begin".len + data.len + "end".len; expectEqual(expected_file_size, file_size); var buf_stream = io.bufferedReader(file.reader()); const st = buf_stream.reader(); const contents = try st.readAllAlloc(std.testing.allocator, 2 * 1024); defer std.testing.allocator.free(contents); expect(mem.eql(u8, contents[0.."begin".len], "begin")); expect(mem.eql(u8, contents["begin".len .. contents.len - "end".len], &data)); expect(mem.eql(u8, contents[contents.len - "end".len ..], "end")); } try tmp.dir.deleteFile(tmp_file_name); } test "BitStreams with File Stream" { var tmp = tmpDir(.{}); defer tmp.cleanup(); const tmp_file_name = "temp_test_file.txt"; { var file = try tmp.dir.createFile(tmp_file_name, .{}); defer file.close(); var bit_stream = io.bitOutStream(builtin.endian, file.outStream()); try bit_stream.writeBits(@as(u2, 1), 1); try bit_stream.writeBits(@as(u5, 2), 2); try bit_stream.writeBits(@as(u128, 3), 3); try bit_stream.writeBits(@as(u8, 4), 4); try bit_stream.writeBits(@as(u9, 5), 5); try bit_stream.writeBits(@as(u1, 1), 1); try bit_stream.flushBits(); } { var file = try tmp.dir.openFile(tmp_file_name, .{}); defer file.close(); var bit_stream = io.bitReader(builtin.endian, file.reader()); var out_bits: usize = undefined; expect(1 == try bit_stream.readBits(u2, 1, &out_bits)); expect(out_bits == 1); expect(2 == try bit_stream.readBits(u5, 2, &out_bits)); expect(out_bits == 2); expect(3 == try bit_stream.readBits(u128, 3, &out_bits)); expect(out_bits == 3); expect(4 == try bit_stream.readBits(u8, 4, &out_bits)); expect(out_bits == 4); expect(5 == try bit_stream.readBits(u9, 5, &out_bits)); expect(out_bits == 5); expect(1 == try bit_stream.readBits(u1, 1, &out_bits)); expect(out_bits == 1); expectError(error.EndOfStream, bit_stream.readBitsNoEof(u1, 1)); } try tmp.dir.deleteFile(tmp_file_name); } test "File seek ops" { var tmp = tmpDir(.{}); defer tmp.cleanup(); const tmp_file_name = "temp_test_file.txt"; var file = try tmp.dir.createFile(tmp_file_name, .{}); defer { file.close(); tmp.dir.deleteFile(tmp_file_name) catch {}; } try file.writeAll(&([_]u8{0x55} ** 8192)); // Seek to the end try file.seekFromEnd(0); expect((try file.getPos()) == try file.getEndPos()); // Negative delta try file.seekBy(-4096); expect((try file.getPos()) == 4096); // Positive delta try file.seekBy(10); expect((try file.getPos()) == 4106); // Absolute position try file.seekTo(1234); expect((try file.getPos()) == 1234); } test "setEndPos" { var tmp = tmpDir(.{}); defer tmp.cleanup(); const tmp_file_name = "temp_test_file.txt"; var file = try tmp.dir.createFile(tmp_file_name, .{}); defer { file.close(); tmp.dir.deleteFile(tmp_file_name) catch {}; } // Verify that the file size changes and the file offset is not moved std.testing.expect((try file.getEndPos()) == 0); std.testing.expect((try file.getPos()) == 0); try file.setEndPos(8192); std.testing.expect((try file.getEndPos()) == 8192); std.testing.expect((try file.getPos()) == 0); try file.seekTo(100); try file.setEndPos(4096); std.testing.expect((try file.getEndPos()) == 4096); std.testing.expect((try file.getPos()) == 100); try file.setEndPos(0); std.testing.expect((try file.getEndPos()) == 0); std.testing.expect((try file.getPos()) == 100); } test "updateTimes" { var tmp = tmpDir(.{}); defer tmp.cleanup(); const tmp_file_name = "just_a_temporary_file.txt"; var file = try tmp.dir.createFile(tmp_file_name, .{ .read = true }); defer { file.close(); tmp.dir.deleteFile(tmp_file_name) catch {}; } var stat_old = try file.stat(); // Set atime and mtime to 5s before try file.updateTimes( stat_old.atime - 5 * std.time.ns_per_s, stat_old.mtime - 5 * std.time.ns_per_s, ); var stat_new = try file.stat(); expect(stat_new.atime < stat_old.atime); expect(stat_new.mtime < stat_old.mtime); }
lib/std/io/test.zig
const tests = @import("tests.zig"); const builtin = @import("builtin"); // add_both - test for stage1 and stage2, in #include mode // add - test stage1 only, in #include mode // add_2 - test stage2 only // addC_both - test for stage1 and stage2, in -c mode // addC - test stage1 only, in -c mode pub fn addCases(cases: *tests.TranslateCContext) void { /////////////// Cases that pass for both stage1/stage2 //////////////// cases.add_both("simple function prototypes", \\void __attribute__((noreturn)) foo(void); \\int bar(void); , &[_][]const u8{ \\pub extern fn foo() noreturn; \\pub extern fn bar() c_int; }); cases.addC_both("simple var decls", \\void foo(void) { \\ int a; \\ char b = 123; \\ const int c; \\ const unsigned d = 440; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = undefined; \\ var b: u8 = @as(u8, 123); \\ const c: c_int = undefined; \\ const d: c_uint = @as(c_uint, 440); \\} }); cases.addC_both("ignore result, explicit function arguments", \\void foo(void) { \\ int a; \\ 1; \\ "hey"; \\ 1 + 1; \\ 1 - 1; \\ a = 1; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = undefined; \\ _ = 1; \\ _ = "hey"; \\ _ = (1 + 1); \\ _ = (1 - 1); \\ a = 1; \\} }); cases.addC_both("variables", \\extern int extern_var; \\static const int int_var = 13; , &[_][]const u8{ \\pub extern var extern_var: c_int; , \\pub const int_var: c_int = 13; }); cases.add_both("const ptr initializer", \\static const char *v0 = "0.0.0"; , &[_][]const u8{ \\pub var v0: [*c]const u8 = "0.0.0"; }); cases.addC_both("static incomplete array inside function", \\void foo(void) { \\ static const char v2[] = "2.2.2"; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ const v2: [*c]const u8 = "2.2.2"; \\} }); cases.addC_both("simple function definition", \\void foo(void) {} \\static void bar(void) {} , &[_][]const u8{ \\pub export fn foo() void {} \\pub fn bar() void {} }); cases.add_both("typedef void", \\typedef void Foo; \\Foo fun(Foo *a); , &[_][]const u8{ \\pub const Foo = c_void; , \\pub extern fn fun(a: ?*Foo) Foo; }); cases.add_both("duplicate typedef", \\typedef long foo; \\typedef int bar; \\typedef long foo; \\typedef int baz; , &[_][]const u8{ \\pub const foo = c_long; \\pub const bar = c_int; \\pub const baz = c_int; }); cases.addC_both("casting pointers to ints and ints to pointers", \\void foo(void); \\void bar(void) { \\ void *func_ptr = foo; \\ void (*typed_func_ptr)(void) = (void (*)(void)) (unsigned long) func_ptr; \\} , &[_][]const u8{ \\pub extern fn foo() void; \\pub export fn bar() void { \\ var func_ptr: ?*c_void = @ptrCast(?*c_void, foo); \\ var typed_func_ptr: ?extern fn () void = @intToPtr(?extern fn () void, @as(c_ulong, @ptrToInt(func_ptr))); \\} }); cases.add_both("noreturn attribute", \\void foo(void) __attribute__((noreturn)); , &[_][]const u8{ \\pub extern fn foo() noreturn; }); cases.addC_both("add, sub, mul, div, rem", \\int s() { \\ int a, b, c; \\ c = a + b; \\ c = a - b; \\ c = a * b; \\ c = a / b; \\ c = a % b; \\} \\unsigned u() { \\ unsigned a, b, c; \\ c = a + b; \\ c = a - b; \\ c = a * b; \\ c = a / b; \\ c = a % b; \\} , &[_][]const u8{ \\pub export fn s() c_int { \\ var a: c_int = undefined; \\ var b: c_int = undefined; \\ var c: c_int = undefined; \\ c = (a + b); \\ c = (a - b); \\ c = (a * b); \\ c = @divTrunc(a, b); \\ c = @rem(a, b); \\} \\pub export fn u() c_uint { \\ var a: c_uint = undefined; \\ var b: c_uint = undefined; \\ var c: c_uint = undefined; \\ c = (a +% b); \\ c = (a -% b); \\ c = (a *% b); \\ c = (a / b); \\ c = (a % b); \\} }); cases.add_both("typedef of function in struct field", \\typedef void lws_callback_function(void); \\struct Foo { \\ void (*func)(void); \\ lws_callback_function *callback_http; \\}; , &[_][]const u8{ \\pub const lws_callback_function = extern fn () void; \\pub const struct_Foo = extern struct { \\ func: ?extern fn () void, \\ callback_http: ?lws_callback_function, \\}; }); cases.add_both("pointer to struct demoted to opaque due to bit fields", \\struct Foo { \\ unsigned int: 1; \\}; \\struct Bar { \\ struct Foo *foo; \\}; , &[_][]const u8{ \\pub const struct_Foo = @OpaqueType(); , \\pub const struct_Bar = extern struct { \\ foo: ?*struct_Foo, \\}; }); cases.add_both("macro with left shift", \\#define REDISMODULE_READ (1<<0) , &[_][]const u8{ \\pub const REDISMODULE_READ = 1 << 0; }); cases.add_both("double define struct", \\typedef struct Bar Bar; \\typedef struct Foo Foo; \\ \\struct Foo { \\ Foo *a; \\}; \\ \\struct Bar { \\ Foo *a; \\}; , &[_][]const u8{ \\pub const struct_Foo = extern struct { \\ a: [*c]Foo, \\}; , \\pub const Foo = struct_Foo; , \\pub const struct_Bar = extern struct { \\ a: [*c]Foo, \\}; , \\pub const Bar = struct_Bar; }); cases.add_both("simple struct", \\struct Foo { \\ int x; \\ char *y; \\}; , &[_][]const u8{ \\const struct_Foo = extern struct { \\ x: c_int, \\ y: [*c]u8, \\}; , \\pub const Foo = struct_Foo; }); cases.add_both("self referential struct with function pointer", \\struct Foo { \\ void (*derp)(struct Foo *foo); \\}; , &[_][]const u8{ \\pub const struct_Foo = extern struct { \\ derp: ?extern fn ([*c]struct_Foo) void, \\}; , \\pub const Foo = struct_Foo; }); cases.add_both("struct prototype used in func", \\struct Foo; \\struct Foo *some_func(struct Foo *foo, int x); , &[_][]const u8{ \\pub const struct_Foo = @OpaqueType(); , \\pub extern fn some_func(foo: ?*struct_Foo, x: c_int) ?*struct_Foo; , \\pub const Foo = struct_Foo; }); cases.add_both("#define an unsigned integer literal", \\#define CHANNEL_COUNT 24 , &[_][]const u8{ \\pub const CHANNEL_COUNT = 24; }); cases.add_both("#define referencing another #define", \\#define THING2 THING1 \\#define THING1 1234 , &[_][]const u8{ \\pub const THING1 = 1234; , \\pub const THING2 = THING1; }); cases.add_both("circular struct definitions", \\struct Bar; \\ \\struct Foo { \\ struct Bar *next; \\}; \\ \\struct Bar { \\ struct Foo *next; \\}; , &[_][]const u8{ \\pub const struct_Bar = extern struct { \\ next: [*c]struct_Foo, \\}; , \\pub const struct_Foo = extern struct { \\ next: [*c]struct_Bar, \\}; }); cases.add_both("#define string", \\#define foo "a string" , &[_][]const u8{ \\pub const foo = "a string"; }); cases.add_both("zig keywords in C code", \\struct comptime { \\ int defer; \\}; , &[_][]const u8{ \\pub const struct_comptime = extern struct { \\ @"defer": c_int, \\}; , \\pub const @"comptime" = struct_comptime; }); cases.add_both("macro with parens around negative number", \\#define LUA_GLOBALSINDEX (-10002) , &[_][]const u8{ \\pub const LUA_GLOBALSINDEX = -10002; }); cases.add_both( "u integer suffix after 0 (zero) in macro definition", "#define ZERO 0U", &[_][]const u8{ "pub const ZERO = @as(c_uint, 0);", }, ); cases.add_both( "l integer suffix after 0 (zero) in macro definition", "#define ZERO 0L", &[_][]const u8{ "pub const ZERO = @as(c_long, 0);", }, ); cases.add_both( "ul integer suffix after 0 (zero) in macro definition", "#define ZERO 0UL", &[_][]const u8{ "pub const ZERO = @as(c_ulong, 0);", }, ); cases.add_both( "lu integer suffix after 0 (zero) in macro definition", "#define ZERO 0LU", &[_][]const u8{ "pub const ZERO = @as(c_ulong, 0);", }, ); cases.add_both( "ll integer suffix after 0 (zero) in macro definition", "#define ZERO 0LL", &[_][]const u8{ "pub const ZERO = @as(c_longlong, 0);", }, ); cases.add_both( "ull integer suffix after 0 (zero) in macro definition", "#define ZERO 0ULL", &[_][]const u8{ "pub const ZERO = @as(c_ulonglong, 0);", }, ); cases.add_both( "llu integer suffix after 0 (zero) in macro definition", "#define ZERO 0LLU", &[_][]const u8{ "pub const ZERO = @as(c_ulonglong, 0);", }, ); cases.add_both( "bitwise not on u-suffixed 0 (zero) in macro definition", "#define NOT_ZERO (~0U)", &[_][]const u8{ "pub const NOT_ZERO = ~@as(c_uint, 0);", }, ); cases.addC_both("null statements", \\void foo(void) { \\ ;;;;; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ {} \\ {} \\ {} \\ {} \\ {} \\} }); if (builtin.os != builtin.Os.windows) { // Windows treats this as an enum with type c_int cases.add_both("big negative enum init values when C ABI supports long long enums", \\enum EnumWithInits { \\ VAL01 = 0, \\ VAL02 = 1, \\ VAL03 = 2, \\ VAL04 = 3, \\ VAL05 = -1, \\ VAL06 = -2, \\ VAL07 = -3, \\ VAL08 = -4, \\ VAL09 = VAL02 + VAL08, \\ VAL10 = -1000012000, \\ VAL11 = -1000161000, \\ VAL12 = -1000174001, \\ VAL13 = VAL09, \\ VAL14 = VAL10, \\ VAL15 = VAL11, \\ VAL16 = VAL13, \\ VAL17 = (VAL16 - VAL10 + 1), \\ VAL18 = 0x1000000000000000L, \\ VAL19 = VAL18 + VAL18 + VAL18 - 1, \\ VAL20 = VAL19 + VAL19, \\ VAL21 = VAL20 + 0xFFFFFFFFFFFFFFFF, \\ VAL22 = 0xFFFFFFFFFFFFFFFF + 1, \\ VAL23 = 0xFFFFFFFFFFFFFFFF, \\}; , &[_][]const u8{ \\pub const enum_EnumWithInits = extern enum(c_longlong) { \\ VAL01 = 0, \\ VAL02 = 1, \\ VAL03 = 2, \\ VAL04 = 3, \\ VAL05 = -1, \\ VAL06 = -2, \\ VAL07 = -3, \\ VAL08 = -4, \\ VAL09 = -3, \\ VAL10 = -1000012000, \\ VAL11 = -1000161000, \\ VAL12 = -1000174001, \\ VAL13 = -3, \\ VAL14 = -1000012000, \\ VAL15 = -1000161000, \\ VAL16 = -3, \\ VAL17 = 1000011998, \\ VAL18 = 1152921504606846976, \\ VAL19 = 3458764513820540927, \\ VAL20 = 6917529027641081854, \\ VAL21 = 6917529027641081853, \\ VAL22 = 0, \\ VAL23 = -1, \\}; }); } cases.addC_both("predefined expressions", \\void foo(void) { \\ __func__; \\ __FUNCTION__; \\ __PRETTY_FUNCTION__; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ _ = "foo"; \\ _ = "foo"; \\ _ = "void foo(void)"; \\} }); cases.addC_both("ignore result, no function arguments", \\void foo() { \\ int a; \\ 1; \\ "hey"; \\ 1 + 1; \\ 1 - 1; \\ a = 1; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = undefined; \\ _ = 1; \\ _ = "hey"; \\ _ = (1 + 1); \\ _ = (1 - 1); \\ a = 1; \\} }); cases.add_both("constant size array", \\void func(int array[20]); , &[_][]const u8{ \\pub extern fn func(array: [*c]c_int) void; }); cases.add_both("__cdecl doesn't mess up function pointers", \\void foo(void (__cdecl *fn_ptr)(void)); , &[_][]const u8{ \\pub extern fn foo(fn_ptr: ?extern fn () void) void; }); cases.addC_both("void cast", \\void foo() { \\ int a; \\ (void) a; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = undefined; \\ _ = a; \\} }); cases.addC_both("implicit cast to void *", \\void *foo() { \\ unsigned short *x; \\ return x; \\} , &[_][]const u8{ \\pub export fn foo() ?*c_void { \\ var x: [*c]c_ushort = undefined; \\ return @ptrCast(?*c_void, x); \\} }); cases.addC_both("null pointer implicit cast", \\int* foo(void) { \\ return 0; \\} , &[_][]const u8{ \\pub export fn foo() [*c]c_int { \\ return null; \\} }); cases.add_both("simple union", \\union Foo { \\ int x; \\ double y; \\}; , &[_][]const u8{ \\pub const union_Foo = extern union { \\ x: c_int, \\ y: f64, \\}; , \\pub const Foo = union_Foo; }); cases.addC_both("string literal", \\const char *foo(void) { \\ return "bar"; \\} , &[_][]const u8{ \\pub export fn foo() [*c]const u8 { \\ return "bar"; \\} }); cases.addC_both("return void", \\void foo(void) { \\ return; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ return; \\} }); cases.addC_both("for loop", \\void foo(void) { \\ for (int i = 0; i; i = i + 1) { } \\} , &[_][]const u8{ \\pub export fn foo() void { \\ { \\ var i: c_int = 0; \\ while (i != 0) : (i = (i + 1)) {} \\ } \\} }); cases.addC_both("empty for loop", \\void foo(void) { \\ for (;;) { } \\} , &[_][]const u8{ \\pub export fn foo() void { \\ while (true) {} \\} }); cases.addC_both("break statement", \\void foo(void) { \\ for (;;) { \\ break; \\ } \\} , &[_][]const u8{ \\pub export fn foo() void { \\ while (true) { \\ break; \\ } \\} }); cases.addC_both("continue statement", \\void foo(void) { \\ for (;;) { \\ continue; \\ } \\} , &[_][]const u8{ \\pub export fn foo() void { \\ while (true) { \\ continue; \\ } \\} }); cases.addC_both("pointer casting", \\float *ptrcast() { \\ int *a; \\ return (float *)a; \\} , &[_][]const u8{ \\pub export fn ptrcast() [*c]f32 { \\ var a: [*c]c_int = undefined; \\ return @ptrCast([*c]f32, @alignCast(@alignOf(f32), a)); \\} }); cases.addC_both("pointer conversion with different alignment", \\void test_ptr_cast() { \\ void *p; \\ { \\ char *to_char = (char *)p; \\ short *to_short = (short *)p; \\ int *to_int = (int *)p; \\ long long *to_longlong = (long long *)p; \\ } \\ { \\ char *to_char = p; \\ short *to_short = p; \\ int *to_int = p; \\ long long *to_longlong = p; \\ } \\} , &[_][]const u8{ \\pub export fn test_ptr_cast() void { \\ var p: ?*c_void = undefined; \\ { \\ var to_char: [*c]u8 = @ptrCast([*c]u8, @alignCast(@alignOf(u8), p)); \\ var to_short: [*c]c_short = @ptrCast([*c]c_short, @alignCast(@alignOf(c_short), p)); \\ var to_int: [*c]c_int = @ptrCast([*c]c_int, @alignCast(@alignOf(c_int), p)); \\ var to_longlong: [*c]c_longlong = @ptrCast([*c]c_longlong, @alignCast(@alignOf(c_longlong), p)); \\ } \\ { \\ var to_char: [*c]u8 = @ptrCast([*c]u8, @alignCast(@alignOf(u8), p)); \\ var to_short: [*c]c_short = @ptrCast([*c]c_short, @alignCast(@alignOf(c_short), p)); \\ var to_int: [*c]c_int = @ptrCast([*c]c_int, @alignCast(@alignOf(c_int), p)); \\ var to_longlong: [*c]c_longlong = @ptrCast([*c]c_longlong, @alignCast(@alignOf(c_longlong), p)); \\ } \\} }); cases.addC_both("while on non-bool", \\int while_none_bool() { \\ int a; \\ float b; \\ void *c; \\ while (a) return 0; \\ while (b) return 1; \\ while (c) return 2; \\ return 3; \\} , &[_][]const u8{ \\pub export fn while_none_bool() c_int { \\ var a: c_int = undefined; \\ var b: f32 = undefined; \\ var c: ?*c_void = undefined; \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; \\ return 3; \\} }); cases.addC_both("for on non-bool", \\int for_none_bool() { \\ int a; \\ float b; \\ void *c; \\ for (;a;) return 0; \\ for (;b;) return 1; \\ for (;c;) return 2; \\ return 3; \\} , &[_][]const u8{ \\pub export fn for_none_bool() c_int { \\ var a: c_int = undefined; \\ var b: f32 = undefined; \\ var c: ?*c_void = undefined; \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; \\ return 3; \\} }); cases.addC_both("bitshift", \\int foo(void) { \\ return (1 << 2) >> 1; \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ return (1 << @as(@import("std").math.Log2Int(c_int), 2)) >> @as(@import("std").math.Log2Int(c_int), 1); \\} }); cases.addC_both("sizeof", \\#include <stddef.h> \\size_t size_of(void) { \\ return sizeof(int); \\} , &[_][]const u8{ \\pub export fn size_of() usize { \\ return @sizeOf(c_int); \\} }); cases.addC_both("normal deref", \\void foo() { \\ int *x; \\ *x = 1; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var x: [*c]c_int = undefined; \\ x.?.* = 1; \\} }); cases.addC_both("address of operator", \\int foo(void) { \\ int x = 1234; \\ int *ptr = &x; \\ return *ptr; \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ var x: c_int = 1234; \\ var ptr: [*c]c_int = &x; \\ return ptr.?.*; \\} }); cases.addC_both("bin not", \\int foo() { \\ int x; \\ return ~x; \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ var x: c_int = undefined; \\ return ~x; \\} }); cases.addC_both("bool not", \\int foo() { \\ int a; \\ float b; \\ void *c; \\ return !(a == 0); \\ return !a; \\ return !b; \\ return !c; \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ var a: c_int = undefined; \\ var b: f32 = undefined; \\ var c: ?*c_void = undefined; \\ return !(a == 0); \\ return !(a != 0); \\ return !(b != 0); \\ return !(c != null); \\} }); cases.addC("__extension__ cast", \\int foo(void) { \\ return __extension__ 1; \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ return 1; \\} }); if (builtin.os != builtin.Os.windows) { // sysv_abi not currently supported on windows cases.add_both("Macro qualified functions", \\void __attribute__((sysv_abi)) foo(void); , &[_][]const u8{ \\pub extern fn foo() void; }); } /////////////// Cases that pass for only stage2 //////////////// cases.add_2("Parameterless function prototypes", \\void a() {} \\void b(void) {} \\void c(); \\void d(void); , &[_][]const u8{ \\pub export fn a() void {} \\pub export fn b() void {} \\pub extern fn c(...) void; \\pub extern fn d() void; }); cases.add_2("variable declarations", \\extern char arr0[] = "hello"; \\static char arr1[] = "hello"; \\char arr2[] = "hello"; , &[_][]const u8{ \\pub extern var arr0: [*c]u8 = "hello"; \\pub var arr1: [*c]u8 = "hello"; \\pub export var arr2: [*c]u8 = "hello"; }); cases.add_2("array initializer expr", \\static void foo(void){ \\ char arr[10] ={1}; \\ char *arr1[10] ={0}; \\} , &[_][]const u8{ \\pub fn foo() void { \\ var arr: [10]u8 = .{ \\ @as(u8, 1), \\ } ++ .{0} ** 9; \\ var arr1: [10][*c]u8 = .{ \\ null, \\ } ++ .{null} ** 9; \\} }); cases.add_2("enums", \\typedef enum { \\ a, \\ b, \\ c, \\} d; \\enum { \\ e, \\ f = 4, \\ g, \\} h = e; \\struct Baz { \\ enum { \\ i, \\ j, \\ k, \\ } l; \\ d m; \\}; \\enum i { \\ n, \\ o, \\ p, \\}; , &[_][]const u8{ \\pub const a = 0; \\pub const b = 1; \\pub const c = 2; \\const enum_unnamed_1 = extern enum { \\ a, \\ b, \\ c, \\}; \\pub const d = enum_unnamed_1; \\pub const e = 0; \\pub const f = 4; \\pub const g = 5; \\const enum_unnamed_2 = extern enum { \\ e = 0, \\ f = 4, \\ g = 5, \\}; \\pub export var h: enum_unnamed_2 = @intToEnum(enum_unnamed_2, e); \\pub const i = 0; \\pub const j = 1; \\pub const k = 2; \\const enum_unnamed_3 = extern enum { \\ i, \\ j, \\ k, \\}; \\pub const struct_Baz = extern struct { \\ l: enum_unnamed_3, \\ m: d, \\}; \\pub const n = 0; \\pub const o = 1; \\pub const p = 2; \\pub const enum_i = extern enum { \\ n, \\ o, \\ p, \\}; , \\pub const Baz = struct_Baz; }); cases.add_2("#define a char literal", \\#define A_CHAR 'a' , &[_][]const u8{ \\pub const A_CHAR = 'a'; }); cases.add_2("comment after integer literal", \\#define SDL_INIT_VIDEO 0x00000020 /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = 0x00000020; }); cases.add_2("u integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020u /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_uint, 0x00000020); }); cases.add_2("l integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020l /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_long, 0x00000020); }); cases.add_2("ul integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020ul /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulong, 0x00000020); }); cases.add_2("lu integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020lu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulong, 0x00000020); }); cases.add_2("ll integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020ll /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_longlong, 0x00000020); }); cases.add_2("ull integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020ull /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulonglong, 0x00000020); }); cases.add_2("llu integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020llu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulonglong, 0x00000020); }); cases.add_2("generate inline func for #define global extern fn", \\extern void (*fn_ptr)(void); \\#define foo fn_ptr \\ \\extern char (*fn_ptr2)(int, float); \\#define bar fn_ptr2 , &[_][]const u8{ \\pub extern var fn_ptr: ?extern fn () void; , \\pub inline fn foo() void { \\ return fn_ptr.?(); \\} , \\pub extern var fn_ptr2: ?extern fn (c_int, f32) u8; , \\pub inline fn bar(arg_1: c_int, arg_2: f32) u8 { \\ return fn_ptr2.?(arg_1, arg_2); \\} }); cases.add_2("macros with field targets", \\typedef unsigned int GLbitfield; \\typedef void (*PFNGLCLEARPROC) (GLbitfield mask); \\typedef void(*OpenGLProc)(void); \\union OpenGLProcs { \\ OpenGLProc ptr[1]; \\ struct { \\ PFNGLCLEARPROC Clear; \\ } gl; \\}; \\extern union OpenGLProcs glProcs; \\#define glClearUnion glProcs.gl.Clear \\#define glClearPFN PFNGLCLEARPROC , &[_][]const u8{ \\pub const GLbitfield = c_uint; \\pub const PFNGLCLEARPROC = ?extern fn (GLbitfield) void; \\pub const OpenGLProc = ?extern fn () void; \\const struct_unnamed_1 = extern struct { \\ Clear: PFNGLCLEARPROC, \\}; \\pub const union_OpenGLProcs = extern union { \\ ptr: [1]OpenGLProc, \\ gl: struct_unnamed_1, \\}; \\pub extern var glProcs: union_OpenGLProcs; , \\pub const glClearPFN = PFNGLCLEARPROC; , \\pub inline fn glClearUnion(arg_2: GLbitfield) void { \\ return glProcs.gl.Clear.?(arg_2); \\} , \\pub const OpenGLProcs = union_OpenGLProcs; }); cases.add_2("macro pointer cast", \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE) , &[_][]const u8{ \\pub const NRF_GPIO = if (@typeId(@TypeOf(NRF_GPIO_BASE)) == .Pointer) @ptrCast([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else if (@typeId(@TypeOf(NRF_GPIO_BASE)) == .Int) @intToPtr([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else @as([*c]NRF_GPIO_Type, NRF_GPIO_BASE); }); cases.add_2("basic macro function", \\extern int c; \\#define BASIC(c) (c*2) , &[_][]const u8{ \\pub extern var c: c_int; , \\pub inline fn BASIC(c_1: var) @TypeOf(c_1 * 2) { \\ return c_1 * 2; \\} }); cases.add_2("macro defines string literal with hex", \\#define FOO "aoeu\xab derp" \\#define FOO2 "aoeu\x0007a derp" \\#define FOO_CHAR '\xfF' , &[_][]const u8{ \\pub const FOO = "aoeu\xab derp"; , \\pub const FOO2 = "aoeu\x7a derp"; , \\pub const FOO_CHAR = '\xff'; }); cases.add_2("variable aliasing", \\static long a = 2; \\static long b = 2; \\static int c = 4; \\void foo(char c) { \\ int a; \\ char b = 123; \\ b = (char) a; \\ { \\ int d = 5; \\ } \\ unsigned d = 440; \\} , &[_][]const u8{ \\pub var a: c_long = @as(c_long, 2); \\pub var b: c_long = @as(c_long, 2); \\pub var c: c_int = 4; \\pub export fn foo(_arg_c_1: u8) void { \\ var c_1 = _arg_c_1; \\ var a_2: c_int = undefined; \\ var b_3: u8 = @as(u8, 123); \\ b_3 = @as(u8, a_2); \\ { \\ var d: c_int = 5; \\ } \\ var d: c_uint = @as(c_uint, 440); \\} }); cases.add_2("comma operator", \\int foo(char c) { \\ 2, 4; \\ return 2, 4, 6; \\} , &[_][]const u8{ \\pub export fn foo(_arg_c: u8) c_int { \\ var c = _arg_c; \\ _ = 2; \\ _ = 4; \\ _ = 2; \\ _ = 4; \\ return 6; \\} }); cases.add_2("wors-case assign", \\int foo(char c) { \\ int a; \\ int b; \\ a = b = 2; \\} , &[_][]const u8{ \\pub export fn foo(_arg_c: u8) c_int { \\ var c = _arg_c; \\ var a: c_int = undefined; \\ var b: c_int = undefined; \\ a = blk: { \\ const _tmp_1 = 2; \\ b = _tmp_1; \\ break :blk _tmp_1; \\ }; \\} }); cases.add_2("if statements", \\int foo(char c) { \\ if (2) { \\ int a = 2; \\ } \\ if (2, 5) { \\ int a = 2; \\ } \\} , &[_][]const u8{ \\pub export fn foo(_arg_c: u8) c_int { \\ var c = _arg_c; \\ if (2 != 0) { \\ var a: c_int = 2; \\ } \\ if ((blk: { \\ _ = 2; \\ break :blk 5; \\ }) != 0) { \\ var a: c_int = 2; \\ } \\} }); cases.add_2("while loops", \\int foo() { \\ int a = 5; \\ while (2) \\ a = 2; \\ while (4) { \\ int a = 4; \\ a = 9; \\ return 6, a; \\ } \\ do { \\ int a = 2; \\ a = 12; \\ } while (4); \\ do \\ a = 7; \\ while (4); \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ var a: c_int = 5; \\ while (2 != 0) a = 2; \\ while (4 != 0) { \\ var a: c_int = 4; \\ a = 9; \\ _ = 6; \\ return a; \\ } \\ while (true) { \\ var a: c_int = 2; \\ a = 12; \\ if (!(4 != 0)) break; \\ } \\ while (true) { \\ a = 7; \\ if (!(4 != 0)) break; \\ } \\} }); cases.add_2("for loops", \\int foo() { \\ for (int i = 2, b = 4; i + 2; i = 2) { \\ int a = 2; \\ a = 6, 5, 7; \\ } \\ char i = 2; \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ { \\ var i: c_int = 2; \\ var b: c_int = 4; \\ while ((i + 2) != 0) : (i = 2) { \\ var a: c_int = 2; \\ a = 6; \\ _ = 5; \\ _ = 7; \\ } \\ } \\ var i: u8 = @as(u8, 2); \\} }); cases.add_2("shadowing primitive types", \\unsigned anyerror = 2; , &[_][]const u8{ \\pub export var _anyerror: c_uint = @as(c_uint, 2); }); cases.add_2("floats", \\float a = 3.1415; \\double b = 3.1415; \\int c = 3.1415; \\double d = 3; , &[_][]const u8{ \\pub export var a: f32 = @floatCast(f32, 3.1415); \\pub export var b: f64 = 3.1415; \\pub export var c: c_int = @floatToInt(c_int, 3.1415); \\pub export var d: f64 = @intToFloat(f64, 3); }); cases.add_2("conditional operator", \\int bar(void) { \\ if (2 ? 5 : 5 ? 4 : 6) 2; \\ return 2 ? 5 : 5 ? 4 : 6; \\} , &[_][]const u8{ \\pub export fn bar() c_int { \\ if ((if (2 != 0) 5 else (if (5 != 0) 4 else 6)) != 0) _ = 2; \\ return if (2 != 0) 5 else if (5 != 0) 4 else 6; \\} }); cases.add_2("switch on int", \\int switch_fn(int i) { \\ int res = 0; \\ switch (i) { \\ case 0: \\ res = 1; \\ case 1 ... 3: \\ res = 2; \\ default: \\ res = 3 * i; \\ break; \\ case 4: \\ res = 5; \\ } \\} , &[_][]const u8{ \\pub export fn switch_fn(_arg_i: c_int) c_int { \\ var i = _arg_i; \\ var res: c_int = 0; \\ __switch: { \\ __case_2: { \\ __default: { \\ __case_1: { \\ __case_0: { \\ switch (i) { \\ 0 => break :__case_0, \\ 1...3 => break :__case_1, \\ else => break :__default, \\ 4 => break :__case_2, \\ } \\ } \\ res = 1; \\ } \\ res = 2; \\ } \\ res = (3 * i); \\ break :__switch; \\ } \\ res = 5; \\ } \\} }); cases.add_2("type referenced struct", \\struct Foo { \\ struct Bar{ \\ int b; \\ }; \\ struct Bar c; \\}; , &[_][]const u8{ \\pub const struct_Bar = extern struct { \\ b: c_int, \\}; \\pub const struct_Foo = extern struct { \\ c: struct_Bar, \\}; }); cases.add_2("undefined array global", \\int array[100] = {}; , &[_][]const u8{ \\pub export var array: [100]c_int = .{0} ** 100; }); cases.add_2("restrict -> noalias", \\void foo(void *restrict bar, void *restrict); , &[_][]const u8{ \\pub extern fn foo(noalias bar: ?*c_void, noalias ?*c_void) void; }); cases.add_2("assign", \\int max(int a) { \\ int tmp; \\ tmp = a; \\ a = tmp; \\} , &[_][]const u8{ \\pub export fn max(_arg_a: c_int) c_int { \\ var a = _arg_a; \\ var tmp: c_int = undefined; \\ tmp = a; \\ a = tmp; \\} }); cases.add_2("chaining assign", \\void max(int a) { \\ int b, c; \\ c = b = a; \\} , &[_][]const u8{ \\pub export fn max(_arg_a: c_int) void { \\ var a = _arg_a; \\ var b: c_int = undefined; \\ var c: c_int = undefined; \\ c = blk: { \\ const _tmp_1 = a; \\ b = _tmp_1; \\ break :blk _tmp_1; \\ }; \\} }); cases.add_2("anonymous enum", \\enum { \\ One, \\ Two, \\}; , &[_][]const u8{ \\pub const One = 0; \\pub const Two = 1; \\const enum_unnamed_1 = extern enum { \\ One, \\ Two, \\}; }); cases.add_2("c style cast", \\int float_to_int(float a) { \\ return (int)a; \\} , &[_][]const u8{ \\pub export fn float_to_int(_arg_a: f32) c_int { \\ var a = _arg_a; \\ return @floatToInt(c_int, a); \\} }); cases.add_2("escape sequences", \\const char *escapes() { \\char a = '\'', \\ b = '\\', \\ c = '\a', \\ d = '\b', \\ e = '\f', \\ f = '\n', \\ g = '\r', \\ h = '\t', \\ i = '\v', \\ j = '\0', \\ k = '\"'; \\ return "\'\\\a\b\f\n\r\t\v\0\""; \\} \\ , &[_][]const u8{ \\pub export fn escapes() [*c]const u8 { \\ var a: u8 = @as(u8, '\''); \\ var b: u8 = @as(u8, '\\'); \\ var c: u8 = @as(u8, '\x07'); \\ var d: u8 = @as(u8, '\x08'); \\ var e: u8 = @as(u8, '\x0c'); \\ var f: u8 = @as(u8, '\n'); \\ var g: u8 = @as(u8, '\r'); \\ var h: u8 = @as(u8, '\t'); \\ var i: u8 = @as(u8, '\x0b'); \\ var j: u8 = @as(u8, '\x00'); \\ var k: u8 = @as(u8, '\"'); \\ return "\'\\\x07\x08\x0c\n\r\t\x0b\x00\""; \\} }); cases.add_2("do loop", \\void foo(void) { \\ int a = 2; \\ do { \\ a = a - 1; \\ } while (a); \\ \\ int b = 2; \\ do \\ b = b -1; \\ while (b); \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = 2; \\ while (true) { \\ a = (a - 1); \\ if (!(a != 0)) break; \\ } \\ var b: c_int = 2; \\ while (true) { \\ b = (b - 1); \\ if (!(b != 0)) break; \\ } \\} }); cases.add_2("logical and, logical or, on non-bool values, extra parens", \\enum Foo { \\ FooA, \\ FooB, \\ FooC, \\}; \\typedef int SomeTypedef; \\int and_or_non_bool(int a, float b, void *c) { \\ enum Foo d = FooA; \\ int e = (a && b); \\ int f = (b && c); \\ int g = (a && c); \\ int h = (a || b); \\ int i = (b || c); \\ int j = (a || c); \\ int k = (a || d); \\ int l = (d && b); \\ int m = (c || d); \\ SomeTypedef td = 44; \\ int o = (td || b); \\ int p = (c && td); \\ return ((((((((((e + f) + g) + h) + i) + j) + k) + l) + m) + o) + p); \\} , &[_][]const u8{ \\pub const enum_Foo = extern enum { \\ A, \\ B, \\ C, \\}; \\pub const SomeTypedef = c_int; \\pub export fn and_or_non_bool(_arg_a: c_int, _arg_b: f32, _arg_c: ?*c_void) c_int { \\ var a = _arg_a; \\ var b = _arg_b; \\ var c = _arg_c; \\ var d: enum_Foo = @intToEnum(enum_Foo, FooA); \\ var e: c_int = @boolToInt(((a != 0) and (b != 0))); \\ var f: c_int = @boolToInt(((b != 0) and (c != null))); \\ var g: c_int = @boolToInt(((a != 0) and (c != null))); \\ var h: c_int = @boolToInt(((a != 0) or (b != 0))); \\ var i: c_int = @boolToInt(((b != 0) or (c != null))); \\ var j: c_int = @boolToInt(((a != 0) or (c != null))); \\ var k: c_int = @boolToInt(((a != 0) or (@enumToInt(d) != 0))); \\ var l: c_int = @boolToInt(((@enumToInt(d) != 0) and (b != 0))); \\ var m: c_int = @boolToInt(((c != null) or (@enumToInt(d) != 0))); \\ var td: SomeTypedef = 44; \\ var o: c_int = @boolToInt(((td != 0) or (b != 0))); \\ var p: c_int = @boolToInt(((c != null) and (td != 0))); \\ return ((((((((((e + f) + g) + h) + i) + j) + k) + l) + m) + o) + p); \\} , \\pub const Foo = enum_Foo; }); cases.add_2("qualified struct and enum", \\struct Foo { \\ int x; \\ int y; \\}; \\enum Bar { \\ BarA, \\ BarB, \\}; \\void func(struct Foo *a, enum Bar **b); , &[_][]const u8{ \\pub const struct_Foo = extern struct { \\ x: c_int, \\ y: c_int, \\}; , \\pub const enum_Bar = extern enum { \\ A, \\ B, \\}; \\pub extern fn func(a: [*c]struct_Foo, b: [*c][*c]enum_Bar) void; , \\pub const Foo = struct_Foo; \\pub const Bar = enum_Bar; }); cases.add_2("bitwise binary operators, simpler parens", \\int max(int a, int b) { \\ return (a & b) ^ (a | b); \\} , &[_][]const u8{ \\pub export fn max(_arg_a: c_int, _arg_b: c_int) c_int { \\ var a = _arg_a; \\ var b = _arg_b; \\ return ((a & b) ^ (a | b)); \\} }); cases.add_2("comparison operators (no if)", // TODO Come up with less contrived tests? Make sure to cover all these comparisons. \\int test_comparisons(int a, int b) { \\ int c = (a < b); \\ int d = (a > b); \\ int e = (a <= b); \\ int f = (a >= b); \\ int g = (c < d); \\ int h = (e < f); \\ int i = (g < h); \\ return i; \\} , &[_][]const u8{ \\pub export fn test_comparisons(_arg_a: c_int, _arg_b: c_int) c_int { \\ var a = _arg_a; \\ var b = _arg_b; \\ var c: c_int = @boolToInt((a < b)); \\ var d: c_int = @boolToInt((a > b)); \\ var e: c_int = @boolToInt((a <= b)); \\ var f: c_int = @boolToInt((a >= b)); \\ var g: c_int = @boolToInt((c < d)); \\ var h: c_int = @boolToInt((e < f)); \\ var i: c_int = @boolToInt((g < h)); \\ return i; \\} }); cases.add_2("==, !=", \\int max(int a, int b) { \\ if (a == b) \\ return a; \\ if (a != b) \\ return b; \\ return a; \\} , &[_][]const u8{ \\pub export fn max(_arg_a: c_int, _arg_b: c_int) c_int { \\ var a = _arg_a; \\ var b = _arg_b; \\ if (a == b) return a; \\ if (a != b) return b; \\ return a; \\} }); cases.add_2("typedeffed bool expression", \\typedef char* yes; \\void foo(void) { \\ yes a; \\ if (a) 2; \\} , &[_][]const u8{ \\pub const yes = [*c]u8; \\pub export fn foo() void { \\ var a: yes = undefined; \\ if (a != null) _ = 2; \\} }); cases.add_2("statement expression", \\int foo(void) { \\ return ({ \\ int a = 1; \\ a; \\ a; \\ }); \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ return (blk: { \\ var a: c_int = 1; \\ _ = a; \\ break :blk a; \\ }); \\} }); cases.add_2("field access expression", \\#define ARROW a->b \\#define DOT a.b \\extern struct Foo { \\ int b; \\}a; \\float b = 2.0f; \\int foo(void) { \\ struct Foo *c; \\ a.b; \\ c->b; \\} , &[_][]const u8{ \\pub const struct_Foo = extern struct { \\ b: c_int, \\}; \\pub extern var a: struct_Foo; \\pub export var b: f32 = 2; \\pub export fn foo() c_int { \\ var c: [*c]struct_Foo = undefined; \\ _ = a.b; \\ _ = c.*.b; \\} , \\pub const DOT = a.b; , \\pub const ARROW = a.*.b; }); cases.add_2("array access", \\#define ACCESS array[2] \\int array[100] = {}; \\int foo(int index) { \\ return array[index]; \\} , &[_][]const u8{ \\pub export var array: [100]c_int = .{0} ** 100; \\pub export fn foo(_arg_index: c_int) c_int { \\ var index = _arg_index; \\ return array[index]; \\} , \\pub const ACCESS = array[2]; }); cases.add_2("macro call", \\#define CALL(arg) bar(arg) , &[_][]const u8{ \\pub inline fn CALL(arg: var) @TypeOf(bar(arg)) { \\ return bar(arg); \\} }); cases.add_2("logical and, logical or", \\int max(int a, int b) { \\ if (a < b || a == b) \\ return b; \\ if (a >= b && a == b) \\ return a; \\ return a; \\} , &[_][]const u8{ \\pub export fn max(_arg_a: c_int, _arg_b: c_int) c_int { \\ var a = _arg_a; \\ var b = _arg_b; \\ if ((a < b) or (a == b)) return b; \\ if ((a >= b) and (a == b)) return a; \\ return a; \\} }); cases.add_2("if statement", \\int max(int a, int b) { \\ if (a < b) \\ return b; \\ \\ if (a < b) \\ return b; \\ else \\ return a; \\ \\ if (a < b) ; else ; \\} , &[_][]const u8{ \\pub export fn max(_arg_a: c_int, _arg_b: c_int) c_int { \\ var a = _arg_a; \\ var b = _arg_b; \\ if (a < b) return b; \\ if (a < b) return b else return a; \\ if (a < b) {} else {} \\} }); cases.add_2("if on non-bool", \\enum SomeEnum { A, B, C }; \\int if_none_bool(int a, float b, void *c, enum SomeEnum d) { \\ if (a) return 0; \\ if (b) return 1; \\ if (c) return 2; \\ if (d) return 3; \\ return 4; \\} , &[_][]const u8{ \\pub const enum_SomeEnum = extern enum { \\ A, \\ B, \\ C, \\}; \\pub export fn if_none_bool(_arg_a: c_int, _arg_b: f32, _arg_c: ?*c_void, _arg_d: enum_SomeEnum) c_int { \\ var a = _arg_a; \\ var b = _arg_b; \\ var c = _arg_c; \\ var d = _arg_d; \\ if (a != 0) return 0; \\ if (b != 0) return 1; \\ if (c != null) return 2; \\ if (d != 0) return 3; \\ return 4; \\} }); cases.add_2("simple data types", \\#include <stdint.h> \\int foo(char a, unsigned char b, signed char c); \\int foo(char a, unsigned char b, signed char c); // test a duplicate prototype \\void bar(uint8_t a, uint16_t b, uint32_t c, uint64_t d); \\void baz(int8_t a, int16_t b, int32_t c, int64_t d); , &[_][]const u8{ \\pub extern fn foo(a: u8, b: u8, c: i8) c_int; \\pub extern fn bar(a: u8, b: u16, c: u32, d: u64) void; \\pub extern fn baz(a: i8, b: i16, c: i32, d: i64) void; }); cases.add_2("simple function", \\int abs(int a) { \\ return a < 0 ? -a : a; \\} , &[_][]const u8{ \\pub export fn abs(_arg_a: c_int) c_int { \\ var a = _arg_a; \\ return if (a < 0) -a else a; \\} }); cases.add_2("post increment", \\unsigned foo1(unsigned a) { \\ a++; \\ return a; \\} \\int foo2(int a) { \\ a++; \\ return a; \\} , &[_][]const u8{ \\pub export fn foo1(_arg_a: c_uint) c_uint { \\ var a = _arg_a; \\ a +%= 1; \\ return a; \\} \\pub export fn foo2(_arg_a: c_int) c_int { \\ var a = _arg_a; \\ a += 1; \\ return a; \\} }); cases.add_2("deref function pointer", \\void foo(void) {} \\int baz(void) { return 0; } \\void bar(void) { \\ void(*f)(void) = foo; \\ int(*b)(void) = baz; \\ f(); \\ (*(f))(); \\ foo(); \\ b(); \\ (*(b))(); \\ baz(); \\} , &[_][]const u8{ \\pub export fn foo() void {} \\pub export fn baz() c_int { \\ return 0; \\} \\pub export fn bar() void { \\ var f: ?extern fn () void = foo; \\ var b: ?extern fn () c_int = baz; \\ f.?(); \\ (f).?(); \\ foo(); \\ _ = b.?(); \\ _ = (b).?(); \\ _ = baz(); \\} }); cases.add_2("pre increment/decrement", \\void foo(void) { \\ int i = 0; \\ unsigned u = 0; \\ ++i; \\ --i; \\ ++u; \\ --u; \\ i = ++i; \\ i = --i; \\ u = ++u; \\ u = --u; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var i: c_int = 0; \\ var u: c_uint = @as(c_uint, 0); \\ i += 1; \\ i -= 1; \\ u +%= 1; \\ u -%= 1; \\ i = (blk: { \\ const _ref_1 = &i; \\ _ref_1.* += 1; \\ break :blk _ref_1.*; \\ }); \\ i = (blk: { \\ const _ref_2 = &i; \\ _ref_2.* -= 1; \\ break :blk _ref_2.*; \\ }); \\ u = (blk: { \\ const _ref_3 = &u; \\ _ref_3.* +%= 1; \\ break :blk _ref_3.*; \\ }); \\ u = (blk: { \\ const _ref_4 = &u; \\ _ref_4.* -%= 1; \\ break :blk _ref_4.*; \\ }); \\} }); cases.add_2("shift right assign", \\int log2(unsigned a) { \\ int i = 0; \\ while (a > 0) { \\ a >>= 1; \\ } \\ return i; \\} , &[_][]const u8{ \\pub export fn log2(_arg_a: c_uint) c_int { \\ var a = _arg_a; \\ var i: c_int = 0; \\ while (a > @as(c_uint, 0)) { \\ a >>= @as(@import("std").math.Log2Int(c_int), 1); \\ } \\ return i; \\} }); cases.add_2("shift right assign with a fixed size type", \\#include <stdint.h> \\int log2(uint32_t a) { \\ int i = 0; \\ while (a > 0) { \\ a >>= 1; \\ } \\ return i; \\} , &[_][]const u8{ \\pub export fn log2(_arg_a: u32) c_int { \\ var a = _arg_a; \\ var i: c_int = 0; \\ while (a > @as(c_uint, 0)) { \\ a >>= @as(@import("std").math.Log2Int(c_int), 1); \\ } \\ return i; \\} }); cases.add_2("compound assignment operators", \\void foo(void) { \\ int a = 0; \\ a += (a += 1); \\ a -= (a -= 1); \\ a *= (a *= 1); \\ a &= (a &= 1); \\ a |= (a |= 1); \\ a ^= (a ^= 1); \\ a >>= (a >>= 1); \\ a <<= (a <<= 1); \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = 0; \\ a += (blk: { \\ const _ref_1 = &a; \\ _ref_1.* = _ref_1.* + 1; \\ break :blk _ref_1.*; \\ }); \\ a -= (blk: { \\ const _ref_2 = &a; \\ _ref_2.* = _ref_2.* - 1; \\ break :blk _ref_2.*; \\ }); \\ a *= (blk: { \\ const _ref_3 = &a; \\ _ref_3.* = _ref_3.* * 1; \\ break :blk _ref_3.*; \\ }); \\ a &= (blk: { \\ const _ref_4 = &a; \\ _ref_4.* = _ref_4.* & 1; \\ break :blk _ref_4.*; \\ }); \\ a |= (blk: { \\ const _ref_5 = &a; \\ _ref_5.* = _ref_5.* | 1; \\ break :blk _ref_5.*; \\ }); \\ a ^= (blk: { \\ const _ref_6 = &a; \\ _ref_6.* = _ref_6.* ^ 1; \\ break :blk _ref_6.*; \\ }); \\ a >>= @as(@import("std").math.Log2Int(c_int), (blk: { \\ const _ref_7 = &a; \\ _ref_7.* = _ref_7.* >> @as(@import("std").math.Log2Int(c_int), 1); \\ break :blk _ref_7.*; \\ })); \\ a <<= @as(@import("std").math.Log2Int(c_int), (blk: { \\ const _ref_8 = &a; \\ _ref_8.* = _ref_8.* << @as(@import("std").math.Log2Int(c_int), 1); \\ break :blk _ref_8.*; \\ })); \\} }); cases.add_2("compound assignment operators unsigned", \\void foo(void) { \\ unsigned a = 0; \\ a += (a += 1); \\ a -= (a -= 1); \\ a *= (a *= 1); \\ a &= (a &= 1); \\ a |= (a |= 1); \\ a ^= (a ^= 1); \\ a >>= (a >>= 1); \\ a <<= (a <<= 1); \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_uint = @as(c_uint, 0); \\ a +%= (blk: { \\ const _ref_1 = &a; \\ _ref_1.* = _ref_1.* +% @as(c_uint, 1); \\ break :blk _ref_1.*; \\ }); \\ a -%= (blk: { \\ const _ref_2 = &a; \\ _ref_2.* = _ref_2.* -% @as(c_uint, 1); \\ break :blk _ref_2.*; \\ }); \\ a *%= (blk: { \\ const _ref_3 = &a; \\ _ref_3.* = _ref_3.* *% @as(c_uint, 1); \\ break :blk _ref_3.*; \\ }); \\ a &= (blk: { \\ const _ref_4 = &a; \\ _ref_4.* = _ref_4.* & @as(c_uint, 1); \\ break :blk _ref_4.*; \\ }); \\ a |= (blk: { \\ const _ref_5 = &a; \\ _ref_5.* = _ref_5.* | @as(c_uint, 1); \\ break :blk _ref_5.*; \\ }); \\ a ^= (blk: { \\ const _ref_6 = &a; \\ _ref_6.* = _ref_6.* ^ @as(c_uint, 1); \\ break :blk _ref_6.*; \\ }); \\ a >>= @as(@import("std").math.Log2Int(c_uint), (blk: { \\ const _ref_7 = &a; \\ _ref_7.* = _ref_7.* >> @as(@import("std").math.Log2Int(c_int), 1); \\ break :blk _ref_7.*; \\ })); \\ a <<= @as(@import("std").math.Log2Int(c_uint), (blk: { \\ const _ref_8 = &a; \\ _ref_8.* = _ref_8.* << @as(@import("std").math.Log2Int(c_int), 1); \\ break :blk _ref_8.*; \\ })); \\} }); cases.add_2("post increment/decrement", \\void foo(void) { \\ int i = 0; \\ unsigned u = 0; \\ i++; \\ i--; \\ u++; \\ u--; \\ i = i++; \\ i = i--; \\ u = u++; \\ u = u--; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var i: c_int = 0; \\ var u: c_uint = @as(c_uint, 0); \\ i += 1; \\ i -= 1; \\ u +%= 1; \\ u -%= 1; \\ i = (blk: { \\ const _ref_1 = &i; \\ const _tmp_2 = _ref_1.*; \\ _ref_1.* += 1; \\ break :blk _tmp_2; \\ }); \\ i = (blk: { \\ const _ref_3 = &i; \\ const _tmp_4 = _ref_3.*; \\ _ref_3.* -= 1; \\ break :blk _tmp_4; \\ }); \\ u = (blk: { \\ const _ref_5 = &u; \\ const _tmp_6 = _ref_5.*; \\ _ref_5.* +%= 1; \\ break :blk _tmp_6; \\ }); \\ u = (blk: { \\ const _ref_7 = &u; \\ const _tmp_8 = _ref_7.*; \\ _ref_7.* -%= 1; \\ break :blk _tmp_8; \\ }); \\} }); cases.add_2("implicit casts", \\#include <stdbool.h> \\ \\void fn_int(int x); \\void fn_f32(float x); \\void fn_f64(double x); \\void fn_char(char x); \\void fn_bool(bool x); \\void fn_ptr(void *x); \\ \\void call(int q) { \\ fn_int(3.0f); \\ fn_int(3.0); \\ fn_int(3.0L); \\ fn_int('ABCD'); \\ fn_f32(3); \\ fn_f64(3); \\ fn_char('3'); \\ fn_char('\x1'); \\ fn_char(0); \\ fn_f32(3.0f); \\ fn_f64(3.0); \\ fn_bool(123); \\ fn_bool(0); \\ fn_bool(&fn_int); \\ fn_int(&fn_int); \\ fn_ptr(42); \\} , &[_][]const u8{ \\pub extern fn fn_int(x: c_int) void; \\pub extern fn fn_f32(x: f32) void; \\pub extern fn fn_f64(x: f64) void; \\pub extern fn fn_char(x: u8) void; \\pub extern fn fn_bool(x: bool) void; \\pub extern fn fn_ptr(x: ?*c_void) void; \\pub export fn call(_arg_q: c_int) void { \\ var q = _arg_q; \\ fn_int(@floatToInt(c_int, 3)); \\ fn_int(@floatToInt(c_int, 3)); \\ fn_int(@floatToInt(c_int, 3)); \\ fn_int(1094861636); \\ fn_f32(@intToFloat(f32, 3)); \\ fn_f64(@intToFloat(f64, 3)); \\ fn_char(@as(u8, '3')); \\ fn_char(@as(u8, '\x01')); \\ fn_char(@as(u8, 0)); \\ fn_f32(3); \\ fn_f64(3); \\ fn_bool(123 != 0); \\ fn_bool(0 != 0); \\ fn_bool(@ptrToInt(&fn_int) != 0); \\ fn_int(@intCast(c_int, @ptrToInt(&fn_int))); \\ fn_ptr(@intToPtr(?*c_void, 42)); \\} }); cases.add_2("function call", \\static void bar(void) { } \\void foo(int *(baz)(void)) { \\ bar(); \\ baz(); \\} , &[_][]const u8{ \\pub fn bar() void {} \\pub export fn foo(_arg_baz: ?extern fn () [*c]c_int) void { \\ var baz = _arg_baz; \\ bar(); \\ _ = baz.?(); \\} }); cases.add_2("macro defines string literal with octal", \\#define FOO "aoeu\023 derp" \\#define FOO2 "aoeu\0234 derp" \\#define FOO_CHAR '\077' , &[_][]const u8{ \\pub const FOO = "aoeu\x13 derp"; , \\pub const FOO2 = "aoeu\x134 derp"; , \\pub const FOO_CHAR = '\x3f'; }); cases.add_2("enums", \\enum Foo { \\ FooA, \\ FooB, \\ Foo1, \\}; , &[_][]const u8{ \\pub const enum_Foo = extern enum { \\ A, \\ B, \\ @"1", \\}; , \\pub const FooA = 0; , \\pub const FooB = 1; , \\pub const Foo1 = 2; , \\pub const Foo = enum_Foo; }); cases.add_2("enums", \\enum Foo { \\ FooA = 2, \\ FooB = 5, \\ Foo1, \\}; , &[_][]const u8{ \\pub const enum_Foo = extern enum { \\ A = 2, \\ B = 5, \\ @"1" = 6, \\}; , \\pub const FooA = 2; , \\pub const FooB = 5; , \\pub const Foo1 = 6; , \\pub const Foo = enum_Foo; }); cases.add_2("macro cast", \\#define FOO(bar) baz((void *)(baz)) , &[_][]const u8{ \\pub inline fn FOO(bar: var) @TypeOf(baz(if (@typeId(@TypeOf(baz)) == .Pointer) @ptrCast([*c]void, baz) else if (@typeId(@TypeOf(baz)) == .Int) @intToPtr([*c]void, baz) else @as([*c]void, baz))) { \\ return baz(if (@typeId(@TypeOf(baz)) == .Pointer) @ptrCast([*c]void, baz) else if (@typeId(@TypeOf(baz)) == .Int) @intToPtr([*c]void, baz) else @as([*c]void, baz)); \\} }); /////////////// Cases for only stage1 because stage2 behavior is better //////////////// cases.addC("Parameterless function prototypes", \\void foo() {} \\void bar(void) {} , &[_][]const u8{ \\pub export fn foo() void {} \\pub export fn bar() void {} }); cases.add("#define a char literal", \\#define A_CHAR 'a' , &[_][]const u8{ \\pub const A_CHAR = 97; }); cases.add("generate inline func for #define global extern fn", \\extern void (*fn_ptr)(void); \\#define foo fn_ptr \\ \\extern char (*fn_ptr2)(int, float); \\#define bar fn_ptr2 , &[_][]const u8{ \\pub extern var fn_ptr: ?extern fn () void; , \\pub inline fn foo() void { \\ return fn_ptr.?(); \\} , \\pub extern var fn_ptr2: ?extern fn (c_int, f32) u8; , \\pub inline fn bar(arg0: c_int, arg1: f32) u8 { \\ return fn_ptr2.?(arg0, arg1); \\} }); cases.add("comment after integer literal", \\#define SDL_INIT_VIDEO 0x00000020 /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = 32; }); cases.add("u integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020u /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_uint, 32); }); cases.add("l integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020l /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_long, 32); }); cases.add("ul integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020ul /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulong, 32); }); cases.add("lu integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020lu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulong, 32); }); cases.add("ll integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020ll /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_longlong, 32); }); cases.add("ull integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020ull /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulonglong, 32); }); cases.add("llu integer suffix after hex literal", \\#define SDL_INIT_VIDEO 0x00000020llu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ , &[_][]const u8{ \\pub const SDL_INIT_VIDEO = @as(c_ulonglong, 32); }); cases.add("macros with field targets", \\typedef unsigned int GLbitfield; \\typedef void (*PFNGLCLEARPROC) (GLbitfield mask); \\typedef void(*OpenGLProc)(void); \\union OpenGLProcs { \\ OpenGLProc ptr[1]; \\ struct { \\ PFNGLCLEARPROC Clear; \\ } gl; \\}; \\extern union OpenGLProcs glProcs; \\#define glClearUnion glProcs.gl.Clear \\#define glClearPFN PFNGLCLEARPROC , &[_][]const u8{ \\pub const GLbitfield = c_uint; , \\pub const PFNGLCLEARPROC = ?extern fn (GLbitfield) void; , \\pub const OpenGLProc = ?extern fn () void; , \\pub const union_OpenGLProcs = extern union { \\ ptr: [1]OpenGLProc, \\ gl: extern struct { \\ Clear: PFNGLCLEARPROC, \\ }, \\}; , \\pub extern var glProcs: union_OpenGLProcs; , \\pub const glClearPFN = PFNGLCLEARPROC; , \\pub inline fn glClearUnion(arg0: GLbitfield) void { \\ return glProcs.gl.Clear.?(arg0); \\} , \\pub const OpenGLProcs = union_OpenGLProcs; }); cases.add("macro pointer cast", \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE) , &[_][]const u8{ \\pub const NRF_GPIO = if (@typeId(@TypeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Pointer) @ptrCast([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else if (@typeId(@TypeOf(NRF_GPIO_BASE)) == @import("builtin").TypeId.Int) @intToPtr([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else @as([*c]NRF_GPIO_Type, NRF_GPIO_BASE); }); cases.add("switch on int", \\int switch_fn(int i) { \\ int res = 0; \\ switch (i) { \\ case 0: \\ res = 1; \\ case 1: \\ res = 2; \\ default: \\ res = 3 * i; \\ break; \\ case 2: \\ res = 5; \\ } \\} , &[_][]const u8{ \\pub fn switch_fn(i: c_int) c_int { \\ var res: c_int = 0; \\ __switch: { \\ __case_2: { \\ __default: { \\ __case_1: { \\ __case_0: { \\ switch (i) { \\ 0 => break :__case_0, \\ 1 => break :__case_1, \\ else => break :__default, \\ 2 => break :__case_2, \\ } \\ } \\ res = 1; \\ } \\ res = 2; \\ } \\ res = (3 * i); \\ break :__switch; \\ } \\ res = 5; \\ } \\} }); cases.add("for loop with var init but empty body", \\void foo(void) { \\ for (int x = 0; x < 10; x++); \\} , &[_][]const u8{ \\pub fn foo() void { \\ { \\ var x: c_int = 0; \\ while (x < 10) : (x += 1) {} \\ } \\} }); cases.add("do while with empty body", \\void foo(void) { \\ do ; while (1); \\} , &[_][]const u8{ // TODO this should be if (1 != 0) break \\pub fn foo() void { \\ while (true) { \\ {} \\ if (!1) break; \\ } \\} }); cases.add("for with empty body", \\void foo(void) { \\ for (;;); \\} , &[_][]const u8{ \\pub fn foo() void { \\ while (true) {} \\} }); cases.add("while with empty body", \\void foo(void) { \\ while (1); \\} , &[_][]const u8{ \\pub fn foo() void { \\ while (1 != 0) {} \\} }); cases.add("undefined array global", \\int array[100]; , &[_][]const u8{ \\pub var array: [100]c_int = undefined; }); cases.add("qualified struct and enum", \\struct Foo { \\ int x; \\ int y; \\}; \\enum Bar { \\ BarA, \\ BarB, \\}; \\void func(struct Foo *a, enum Bar **b); , &[_][]const u8{ \\pub const struct_Foo = extern struct { \\ x: c_int, \\ y: c_int, \\}; , \\pub const enum_Bar = extern enum { \\ A, \\ B, \\}; , \\pub const BarA = enum_Bar.A; , \\pub const BarB = enum_Bar.B; , \\pub extern fn func(a: [*c]struct_Foo, b: [*c]([*c]enum_Bar)) void; , \\pub const Foo = struct_Foo; , \\pub const Bar = enum_Bar; }); cases.add("restrict -> noalias", \\void foo(void *restrict bar, void *restrict); , &[_][]const u8{ \\pub extern fn foo(noalias bar: ?*c_void, noalias arg1: ?*c_void) void; }); cases.addC("assign", \\int max(int a) { \\ int tmp; \\ tmp = a; \\ a = tmp; \\} , &[_][]const u8{ \\pub export fn max(_arg_a: c_int) c_int { \\ var a = _arg_a; \\ var tmp: c_int = undefined; \\ tmp = a; \\ a = tmp; \\} }); cases.addC("chaining assign", \\void max(int a) { \\ int b, c; \\ c = b = a; \\} , &[_][]const u8{ \\pub export fn max(a: c_int) void { \\ var b: c_int = undefined; \\ var c: c_int = undefined; \\ c = (x: { \\ const _tmp = a; \\ b = _tmp; \\ break :x _tmp; \\ }); \\} }); cases.add("anonymous enum", \\enum { \\ One, \\ Two, \\}; , &[_][]const u8{ \\pub const One = 0; \\pub const Two = 1; }); cases.addC("c style cast", \\int float_to_int(float a) { \\ return (int)a; \\} , &[_][]const u8{ \\pub export fn float_to_int(a: f32) c_int { \\ return @as(c_int, a); \\} }); cases.addC("comma operator", \\int foo(void) { \\ return 1, 2; \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ return x: { \\ _ = 1; \\ break :x 2; \\ }; \\} }); cases.addC("escape sequences", \\const char *escapes() { \\char a = '\'', \\ b = '\\', \\ c = '\a', \\ d = '\b', \\ e = '\f', \\ f = '\n', \\ g = '\r', \\ h = '\t', \\ i = '\v', \\ j = '\0', \\ k = '\"'; \\ return "\'\\\a\b\f\n\r\t\v\0\""; \\} \\ , &[_][]const u8{ \\pub export fn escapes() [*c]const u8 { \\ var a: u8 = @as(u8, '\''); \\ var b: u8 = @as(u8, '\\'); \\ var c: u8 = @as(u8, '\x07'); \\ var d: u8 = @as(u8, '\x08'); \\ var e: u8 = @as(u8, '\x0c'); \\ var f: u8 = @as(u8, '\n'); \\ var g: u8 = @as(u8, '\r'); \\ var h: u8 = @as(u8, '\t'); \\ var i: u8 = @as(u8, '\x0b'); \\ var j: u8 = @as(u8, '\x00'); \\ var k: u8 = @as(u8, '\"'); \\ return "\'\\\x07\x08\x0c\n\r\t\x0b\x00\""; \\} \\ }); cases.addC("do loop", \\void foo(void) { \\ int a = 2; \\ do { \\ a--; \\ } while (a != 0); \\ \\ int b = 2; \\ do \\ b--; \\ while (b != 0); \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = 2; \\ while (true) { \\ a -= 1; \\ if (!(a != 0)) break; \\ } \\ var b: c_int = 2; \\ while (true) { \\ b -= 1; \\ if (!(b != 0)) break; \\ } \\} }); cases.addC("==, !=", \\int max(int a, int b) { \\ if (a == b) \\ return a; \\ if (a != b) \\ return b; \\ return a; \\} , &[_][]const u8{ \\pub export fn max(a: c_int, b: c_int) c_int { \\ if (a == b) return a; \\ if (a != b) return b; \\ return a; \\} }); cases.addC("bitwise binary operators", \\int max(int a, int b) { \\ return (a & b) ^ (a | b); \\} , &[_][]const u8{ \\pub export fn max(a: c_int, b: c_int) c_int { \\ return (a & b) ^ (a | b); \\} }); cases.addC("statement expression", \\int foo(void) { \\ return ({ \\ int a = 1; \\ a; \\ }); \\} , &[_][]const u8{ \\pub export fn foo() c_int { \\ return x: { \\ var a: c_int = 1; \\ break :x a; \\ }; \\} }); cases.addC("field access expression", \\struct Foo { \\ int field; \\}; \\int read_field(struct Foo *foo) { \\ return foo->field; \\} , &[_][]const u8{ \\pub const struct_Foo = extern struct { \\ field: c_int, \\}; \\pub export fn read_field(foo: [*c]struct_Foo) c_int { \\ return foo.*.field; \\} }); cases.addC("array access", \\int array[100]; \\int foo(int index) { \\ return array[index]; \\} , &[_][]const u8{ \\pub var array: [100]c_int = undefined; \\pub export fn foo(index: c_int) c_int { \\ return array[index]; \\} }); cases.addC("logical and, logical or", \\int max(int a, int b) { \\ if (a < b || a == b) \\ return b; \\ if (a >= b && a == b) \\ return a; \\ return a; \\} , &[_][]const u8{ \\pub export fn max(a: c_int, b: c_int) c_int { \\ if ((a < b) or (a == b)) return b; \\ if ((a >= b) and (a == b)) return a; \\ return a; \\} }); cases.addC("if statement", \\int max(int a, int b) { \\ if (a < b) \\ return b; \\ \\ if (a < b) \\ return b; \\ else \\ return a; \\ \\ if (a < b) ; else ; \\} , &[_][]const u8{ \\pub export fn max(a: c_int, b: c_int) c_int { \\ if (a < b) return b; \\ if (a < b) return b else return a; \\ if (a < b) {} else {} \\} }); cases.add("variable name shadowing", \\int foo(void) { \\ int x = 1; \\ { \\ int x = 2; \\ x += 1; \\ } \\ return x; \\} , &[_][]const u8{ \\pub fn foo() c_int { \\ var x: c_int = 1; \\ { \\ var x_0: c_int = 2; \\ x_0 += 1; \\ } \\ return x; \\} }); cases.add("if on non-bool", \\enum SomeEnum { A, B, C }; \\int if_none_bool(int a, float b, void *c, enum SomeEnum d) { \\ if (a) return 0; \\ if (b) return 1; \\ if (c) return 2; \\ if (d) return 3; \\ return 4; \\} , &[_][]const u8{ \\pub const A = enum_SomeEnum.A; \\pub const B = enum_SomeEnum.B; \\pub const C = enum_SomeEnum.C; \\pub const enum_SomeEnum = extern enum { \\ A, \\ B, \\ C, \\}; \\pub fn if_none_bool(a: c_int, b: f32, c: ?*c_void, d: enum_SomeEnum) c_int { \\ if (a != 0) return 0; \\ if (b != 0) return 1; \\ if (c != null) return 2; \\ if (d != @bitCast(enum_SomeEnum, @as(@TagType(enum_SomeEnum), 0))) return 3; \\ return 4; \\} }); cases.addAllowWarnings("simple data types", \\#include <stdint.h> \\int foo(char a, unsigned char b, signed char c); \\int foo(char a, unsigned char b, signed char c); // test a duplicate prototype \\void bar(uint8_t a, uint16_t b, uint32_t c, uint64_t d); \\void baz(int8_t a, int16_t b, int32_t c, int64_t d); , &[_][]const u8{ \\pub extern fn foo(a: u8, b: u8, c: i8) c_int; , \\pub extern fn bar(a: u8, b: u16, c: u32, d: u64) void; , \\pub extern fn baz(a: i8, b: i16, c: i32, d: i64) void; }); cases.addC("simple function", \\int abs(int a) { \\ return a < 0 ? -a : a; \\} , &[_][]const u8{ \\pub export fn abs(a: c_int) c_int { \\ return if (a < 0) -a else a; \\} }); cases.addC("post increment", \\unsigned foo1(unsigned a) { \\ a++; \\ return a; \\} \\int foo2(int a) { \\ a++; \\ return a; \\} , &[_][]const u8{ \\pub export fn foo1(_arg_a: c_uint) c_uint { \\ var a = _arg_a; \\ a +%= 1; \\ return a; \\} \\pub export fn foo2(_arg_a: c_int) c_int { \\ var a = _arg_a; \\ a += 1; \\ return a; \\} }); cases.addC("deref function pointer", \\void foo(void) {} \\int baz(void) { return 0; } \\void bar(void) { \\ void(*f)(void) = foo; \\ int(*b)(void) = baz; \\ f(); \\ (*(f))(); \\ foo(); \\ b(); \\ (*(b))(); \\ baz(); \\} , &[_][]const u8{ \\pub export fn foo() void {} \\pub export fn baz() c_int { \\ return 0; \\} \\pub export fn bar() void { \\ var f: ?extern fn () void = foo; \\ var b: ?extern fn () c_int = baz; \\ f.?(); \\ f.?(); \\ foo(); \\ _ = b.?(); \\ _ = b.?(); \\ _ = baz(); \\} }); cases.addC("pre increment/decrement", \\void foo(void) { \\ int i = 0; \\ unsigned u = 0; \\ ++i; \\ --i; \\ ++u; \\ --u; \\ i = ++i; \\ i = --i; \\ u = ++u; \\ u = --u; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var i: c_int = 0; \\ var u: c_uint = @as(c_uint, 0); \\ i += 1; \\ i -= 1; \\ u +%= 1; \\ u -%= 1; \\ i = (x: { \\ const _ref = &i; \\ _ref.* += 1; \\ break :x _ref.*; \\ }); \\ i = (x: { \\ const _ref = &i; \\ _ref.* -= 1; \\ break :x _ref.*; \\ }); \\ u = (x: { \\ const _ref = &u; \\ _ref.* +%= 1; \\ break :x _ref.*; \\ }); \\ u = (x: { \\ const _ref = &u; \\ _ref.* -%= 1; \\ break :x _ref.*; \\ }); \\} }); cases.addC("shift right assign", \\int log2(unsigned a) { \\ int i = 0; \\ while (a > 0) { \\ a >>= 1; \\ } \\ return i; \\} , &[_][]const u8{ \\pub export fn log2(_arg_a: c_uint) c_int { \\ var a = _arg_a; \\ var i: c_int = 0; \\ while (a > @as(c_uint, 0)) { \\ a >>= @as(@import("std").math.Log2Int(c_uint), 1); \\ } \\ return i; \\} }); cases.addC("shift right assign with a fixed size type", \\#include <stdint.h> \\int log2(uint32_t a) { \\ int i = 0; \\ while (a > 0) { \\ a >>= 1; \\ } \\ return i; \\} , &[_][]const u8{ \\pub export fn log2(_arg_a: u32) c_int { \\ var a = _arg_a; \\ var i: c_int = 0; \\ while (a > @as(c_uint, 0)) { \\ a >>= @as(u5, 1); \\ } \\ return i; \\} }); cases.addC("compound assignment operators", \\void foo(void) { \\ int a = 0; \\ a += (a += 1); \\ a -= (a -= 1); \\ a *= (a *= 1); \\ a &= (a &= 1); \\ a |= (a |= 1); \\ a ^= (a ^= 1); \\ a >>= (a >>= 1); \\ a <<= (a <<= 1); \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = 0; \\ a += (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* + 1); \\ break :x _ref.*; \\ }); \\ a -= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* - 1); \\ break :x _ref.*; \\ }); \\ a *= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* * 1); \\ break :x _ref.*; \\ }); \\ a &= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* & 1); \\ break :x _ref.*; \\ }); \\ a |= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* | 1); \\ break :x _ref.*; \\ }); \\ a ^= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* ^ 1); \\ break :x _ref.*; \\ }); \\ a >>= @as(@import("std").math.Log2Int(c_int), (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* >> @as(@import("std").math.Log2Int(c_int), 1)); \\ break :x _ref.*; \\ })); \\ a <<= @as(@import("std").math.Log2Int(c_int), (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* << @as(@import("std").math.Log2Int(c_int), 1)); \\ break :x _ref.*; \\ })); \\} }); cases.addC("compound assignment operators unsigned", \\void foo(void) { \\ unsigned a = 0; \\ a += (a += 1); \\ a -= (a -= 1); \\ a *= (a *= 1); \\ a &= (a &= 1); \\ a |= (a |= 1); \\ a ^= (a ^= 1); \\ a >>= (a >>= 1); \\ a <<= (a <<= 1); \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_uint = @as(c_uint, 0); \\ a +%= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* +% @as(c_uint, 1)); \\ break :x _ref.*; \\ }); \\ a -%= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* -% @as(c_uint, 1)); \\ break :x _ref.*; \\ }); \\ a *%= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* *% @as(c_uint, 1)); \\ break :x _ref.*; \\ }); \\ a &= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* & @as(c_uint, 1)); \\ break :x _ref.*; \\ }); \\ a |= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* | @as(c_uint, 1)); \\ break :x _ref.*; \\ }); \\ a ^= (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* ^ @as(c_uint, 1)); \\ break :x _ref.*; \\ }); \\ a >>= @as(@import("std").math.Log2Int(c_uint), (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* >> @as(@import("std").math.Log2Int(c_uint), 1)); \\ break :x _ref.*; \\ })); \\ a <<= @as(@import("std").math.Log2Int(c_uint), (x: { \\ const _ref = &a; \\ _ref.* = (_ref.* << @as(@import("std").math.Log2Int(c_uint), 1)); \\ break :x _ref.*; \\ })); \\} }); cases.addC("post increment/decrement", \\void foo(void) { \\ int i = 0; \\ unsigned u = 0; \\ i++; \\ i--; \\ u++; \\ u--; \\ i = i++; \\ i = i--; \\ u = u++; \\ u = u--; \\} , &[_][]const u8{ \\pub export fn foo() void { \\ var i: c_int = 0; \\ var u: c_uint = @as(c_uint, 0); \\ i += 1; \\ i -= 1; \\ u +%= 1; \\ u -%= 1; \\ i = (x: { \\ const _ref = &i; \\ const _tmp = _ref.*; \\ _ref.* += 1; \\ break :x _tmp; \\ }); \\ i = (x: { \\ const _ref = &i; \\ const _tmp = _ref.*; \\ _ref.* -= 1; \\ break :x _tmp; \\ }); \\ u = (x: { \\ const _ref = &u; \\ const _tmp = _ref.*; \\ _ref.* +%= 1; \\ break :x _tmp; \\ }); \\ u = (x: { \\ const _ref = &u; \\ const _tmp = _ref.*; \\ _ref.* -%= 1; \\ break :x _tmp; \\ }); \\} }); cases.addC("implicit casts", \\#include <stdbool.h> \\ \\void fn_int(int x); \\void fn_f32(float x); \\void fn_f64(double x); \\void fn_char(char x); \\void fn_bool(bool x); \\void fn_ptr(void *x); \\ \\void call(int q) { \\ fn_int(3.0f); \\ fn_int(3.0); \\ fn_int(3.0L); \\ fn_int('ABCD'); \\ fn_f32(3); \\ fn_f64(3); \\ fn_char('3'); \\ fn_char('\x1'); \\ fn_char(0); \\ fn_f32(3.0f); \\ fn_f64(3.0); \\ fn_bool(123); \\ fn_bool(0); \\ fn_bool(&fn_int); \\ fn_int(&fn_int); \\ fn_ptr(42); \\} , &[_][]const u8{ \\pub extern fn fn_int(x: c_int) void; \\pub extern fn fn_f32(x: f32) void; \\pub extern fn fn_f64(x: f64) void; \\pub extern fn fn_char(x: u8) void; \\pub extern fn fn_bool(x: bool) void; \\pub extern fn fn_ptr(x: ?*c_void) void; \\pub export fn call(q: c_int) void { \\ fn_int(@floatToInt(c_int, 3.000000)); \\ fn_int(@floatToInt(c_int, 3.000000)); \\ fn_int(@floatToInt(c_int, 3.000000)); \\ fn_int(1094861636); \\ fn_f32(@intToFloat(f32, 3)); \\ fn_f64(@intToFloat(f64, 3)); \\ fn_char(@as(u8, '3')); \\ fn_char(@as(u8, '\x01')); \\ fn_char(@as(u8, 0)); \\ fn_f32(3.000000); \\ fn_f64(3.000000); \\ fn_bool(true); \\ fn_bool(false); \\ fn_bool(@ptrToInt(&fn_int) != 0); \\ fn_int(@intCast(c_int, @ptrToInt(&fn_int))); \\ fn_ptr(@intToPtr(?*c_void, 42)); \\} }); cases.addC("function call", \\static void bar(void) { } \\void foo(int *(baz)(void)) { \\ bar(); \\ baz(); \\} , &[_][]const u8{ \\pub fn bar() void {} \\pub export fn foo(baz: ?extern fn () [*c]c_int) void { \\ bar(); \\ _ = baz.?(); \\} }); cases.add("macro defines string literal with hex", \\#define FOO "aoeu\xab derp" \\#define FOO2 "aoeu\x0007a derp" \\#define FOO_CHAR '\xfF' , &[_][]const u8{ \\pub const FOO = "aoeu\xab derp"; , \\pub const FOO2 = "aoeuz derp"; , \\pub const FOO_CHAR = 255; }); cases.add("macro defines string literal with octal", \\#define FOO "aoeu\023 derp" \\#define FOO2 "aoeu\0234 derp" \\#define FOO_CHAR '\077' , &[_][]const u8{ \\pub const FOO = "aoeu\x13 derp"; , \\pub const FOO2 = "aoeu\x134 derp"; , \\pub const FOO_CHAR = 63; }); cases.add("enums", \\enum Foo { \\ FooA, \\ FooB, \\ Foo1, \\}; , &[_][]const u8{ \\pub const enum_Foo = extern enum { \\ A, \\ B, \\ @"1", \\}; , \\pub const FooA = enum_Foo.A; , \\pub const FooB = enum_Foo.B; , \\pub const Foo1 = enum_Foo.@"1"; , \\pub const Foo = enum_Foo; }); cases.add("enums", \\enum Foo { \\ FooA = 2, \\ FooB = 5, \\ Foo1, \\}; , &[_][]const u8{ \\pub const enum_Foo = extern enum { \\ A = 2, \\ B = 5, \\ @"1" = 6, \\}; , \\pub const FooA = enum_Foo.A; , \\pub const FooB = enum_Foo.B; , \\pub const Foo1 = enum_Foo.@"1"; , \\pub const Foo = enum_Foo; }); }
test/translate_c.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const maru = @import("maru"); const events = maru.events; const flat = maru.flat; const gfx = maru.gfx; const states = maru.states; usingnamespace maru.math; usingnamespace maru.c; const nitori = @import("nitori"); const Matrix = nitori.matrix.Matrix; //; // react to input events when activated // can use window data to draw pub const Module = struct { const Self = @This(); window: *Window, }; pub const Window = struct { const Self = @This(); top_left: UVec2, width: usize, height: usize, char_buf: Matrix(u8), pub fn init(allocator: *Allocator, top_left: UVec2, width: usize, height: usize) Allocator.Error!Self { var ret = Self{ .top_left = top_left, .width = width, .height = height, .char_buf = try Matrix(u8).init(allocator, width, height), }; var i: usize = 0; while (i < width) : (i += 1) { var j: usize = 0; while (j < height) : (j += 1) { ret.char_buf.get_mut(i, j).* = ' '; } } return ret; } }; pub const Screen = struct { const Self = @This(); // TODO camera_zoom camera_offset: Vec2, windows: ArrayList(Window), tile_w: f32, tile_h: f32, pub fn init(allocator: *Allocator, tile_w: f32, tile_h: f32) Self { return .{ .camera_offset = Vec2.zero(), .windows = ArrayList(Window).init(allocator), .tile_w = tile_w, .tile_h = tile_h, }; } }; //; pub const Programs = struct { const Self = @This(); pixel_sb: flat.Program2d, fn init(workspace_alloc: *Allocator) Allocator.Error!Self { const pixel_sb = flat.Program2d.initDefaultSpritebatch( workspace_alloc, \\ mat3 my_mat3_from_transform2d(float x, float y, float r, float sx, float sy) { \\ mat3 ret = mat3(1.0); \\ float rc = cos(r); \\ float rs = sin(r); \\ ret[0][0] = rc * sx; \\ ret[0][1] = rs * sx; \\ ret[1][0] = -rs * sy; \\ ret[1][1] = rc * sy; \\ //ret[2][0] = floor(x); \\ //ret[2][1] = floor(y); \\ ret[2][0] = x; \\ ret[2][1] = y; \\ return ret; \\ } \\ \\ void my_ready_spritebatch() { \\ // scale main uv coords by sb_uv \\ // automatically handles flip uvs \\ // as long as this is called after flipping the uvs in main (it is) \\ float uv_w = _ext_sb_uv.z - _ext_sb_uv.x; \\ float uv_h = _ext_sb_uv.w - _ext_sb_uv.y; \\ _sb_uv.x = _uv_coord.x * uv_w + _ext_sb_uv.x; \\ _sb_uv.y = _uv_coord.y * uv_h + _ext_sb_uv.y; \\ \\ _sb_color = _ext_sb_color; \\ _sb_model = my_mat3_from_transform2d(_ext_sb_position.x, \\ _ext_sb_position.y, \\ _ext_sb_rotation, \\ _ext_sb_scale.x, \\ _ext_sb_scale.y); \\ } \\ \\vec3 effect() { \\ my_ready_spritebatch(); \\ return _screen * _view * _model * _sb_model * vec3(_ext_vertex, 1.0); \\} , null, ) catch |err| switch (err) { error.OutOfMemory => |e| return e, // TODO dont have unreachable // for if program cant compile on some1s hardware ? // lol at least make an error log // die() instead of unreachable else => unreachable, }; return Self{ .pixel_sb = pixel_sb, }; } fn deinit(self: *Self) void { self.pixel_sb.deinit(); } }; pub const Context = struct { pub const Config = struct { hunk_size: usize, }; // note: use heap alloc for anything thats not temporary heap_alloc: *Allocator, hunk: nitori.hunk.Hunk, gfx_ctx: *const gfx.Context, evs: *const events.EventHandler, draw_defaults: *const flat.DrawDefaults, programs: *const Programs, drawer: *flat.Drawer2d, tm: *maru.frame_timer.FrameTimer, delta_time: f32, screen: Screen, }; pub fn main() anyerror!void { const heap_alloc = std.heap.c_allocator; const cfg = Context.Config{ .hunk_size = 1024 * 2, }; var gfx_ctx: gfx.Context = undefined; try gfx_ctx.init(.{ .window_width = 800, .window_height = 600, }); defer gfx_ctx.deinit(); gfx_ctx.installEventHandler(heap_alloc); var evs = &gfx_ctx.event_handler.?; // glfwSetInputMode(gfx_ctx.window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // TODO use hunk ? var draw_defaults = try flat.DrawDefaults.init(heap_alloc); defer draw_defaults.deinit(); var programs = try Programs.init(heap_alloc); defer programs.deinit(); var drawer = try flat.Drawer2d.init(heap_alloc, .{ .spritebatch_size = 500, .circle_resolution = 50, }); defer drawer.deinit(); var tm = try maru.frame_timer.FrameTimer.start(); // var state_machine = states.StateMachine.init(heap_alloc); // defer state_machine.deinit(); var app_ctx = Context{ .heap_alloc = heap_alloc, .hunk = undefined, .gfx_ctx = &gfx_ctx, .evs = evs, .draw_defaults = &draw_defaults, .programs = &programs, .drawer = &drawer, .tm = &tm, .delta_time = 0, .screen = Screen.init( heap_alloc, @intToFloat(f32, draw_defaults.ibm_font.glyph_width) + 1, @intToFloat(f32, draw_defaults.ibm_font.glyph_height) + 1, ), }; var hunk_mem = try heap_alloc.alloc(u8, cfg.hunk_size); defer heap_alloc.free(hunk_mem); app_ctx.hunk.init(hunk_mem[0..]); //; _ = tm.step(); app_ctx.delta_time = @floatCast(f32, tm.step()); var mouse_held: bool = false; var mouse_was_held: bool = false; var mouse_pos: Vec2 = Vec2.zero(); var mouse_was_pos: Vec2 = Vec2.zero(); try app_ctx.screen.windows.append(try Window.init(heap_alloc, UVec2.init(0, 0), 15, 10)); { var i: usize = 0; while (i < 15) : (i += 1) { var j: usize = 0; while (j < 10) : (j += 1) { app_ctx.screen.windows.items[0].char_buf.get_mut(i, j).* = 'a' + @intCast(u8, i); } } } while (glfwWindowShouldClose(gfx_ctx.window) == GLFW_FALSE) { app_ctx.delta_time = @floatCast(f32, tm.step()); mouse_was_pos = mouse_pos; mouse_was_held = mouse_held; for (evs.mouse_events.items) |m_ev| { switch (m_ev) { .Button => |ev| { if (ev.button == .Left and ev.mods.shift) { mouse_held = ev.action == .Press; } }, .Move => |ev| { mouse_pos = TVec2(f64).init(ev.x, ev.y).cast(f32); }, else => {}, } } if (mouse_held) { const diff = mouse_pos.sub(mouse_was_pos); app_ctx.screen.camera_offset.x += diff.x; app_ctx.screen.camera_offset.y += diff.y; } glClear(GL_COLOR_BUFFER_BIT); { const tile_w = app_ctx.screen.tile_w; const tile_h = app_ctx.screen.tile_h; var sprites = app_ctx.drawer.bindSpritebatch(false, .{ .program = &app_ctx.programs.pixel_sb, .diffuse = &app_ctx.draw_defaults.white_texture, .canvas_width = 800, .canvas_height = 600, }); defer sprites.unbind(); sprites.sprite_color = Color.initRgba(0.95, 0.95, 0.95, 1); sprites.rectangle(0, 0, 800, 600); try sprites.pushCoord(.{ .Translate = app_ctx.screen.camera_offset }); { const cam = app_ctx.screen.camera_offset; // const cam_grid = IVec2.init( // @floatToInt(i32, std.math.floor(cam.x / tile_w)), // @floatToInt(i32, std.math.floor(cam.y / tile_h)), // ); const top_left = Vec2.zero().sub(cam); const top_left_grid = IVec2.init( @floatToInt(i32, std.math.floor(top_left.x / tile_w)), @floatToInt(i32, std.math.floor(top_left.y / tile_h)), ); const bottom_right = top_left.add(Vec2.init(800, 600)); const bottom_right_grid = IVec2.init( @floatToInt(i32, std.math.floor(bottom_right.x / tile_w)), @floatToInt(i32, std.math.floor(bottom_right.y / tile_h)), ); var i: i32 = top_left_grid.x - 1; while (i < bottom_right_grid.x + 1) : (i += 1) { const x = @intToFloat(f32, i) * tile_w; // if (i == 0) { // sprites.sprite_color = Color.initRgba(0.9, 0.3, 0.3, 0.5); // } else { // sprites.sprite_color = Color.initRgba(0.4, 0.4, 0.4, 0.25); // } // // if (@mod(i, 2) != 0) { // sprites.sprite_color.a = 0.1; // } // // sprites.rectangle(x - 1, top_left.y, x + 1, bottom_right.y); if (i == 0) { sprites.sprite_color = Color.initRgba(0.9, 0.3, 0.3, 0.5); sprites.rectangle(x - 1, top_left.y, x + 1, bottom_right.y); } } var j: i32 = top_left_grid.y - 1; while (j < bottom_right_grid.y + 1) : (j += 1) { const y = @intToFloat(f32, j) * tile_h; sprites.sprite_color = Color.initRgba(0.3, 0.3, 0.9, 0.5); if (@mod(j, 2) != 0) { // sprites.sprite_color.a = 0.1; } if (j >= 0) { sprites.rectangle(top_left.x, y - 0.5, bottom_right.x, y + 0.5); } } } for (app_ctx.screen.windows.items) |win| { var top_left = win.top_left.cast(f32); top_left.x *= tile_w; top_left.y *= tile_h; const w = @intToFloat(f32, win.width) * tile_w; const h = @intToFloat(f32, win.height) * tile_h; try sprites.pushCoord(.{ .Translate = top_left }); sprites.sprite_color = Color.white(); sprites.rectangle(0, 0, w, h); sprites.sprite_color = Color.initRgba(0.8, 0.8, 0.8, 1); sprites.rectangle(0, 0, 2, h); sprites.rectangle(0, 0, w, 2); sprites.rectangle(w - 2, 0, w, h); sprites.rectangle(0, h - 2, w, h); sprites.sprite_color = Color.initRgba(0, 0, 0, 1); const font = app_ctx.draw_defaults.ibm_font; var i: usize = 0; var j: usize = 0; while (i < win.width) : (i += 1) { j = 0; while (j < win.height) : (j += 1) { const ch = win.char_buf.get(i, j).*; const x = @intToFloat(f32, i); const y = @intToFloat(f32, j); sprites.setDiffuse(&font.texture); sprites.sprite_uv = font.uvRegion(ch); sprites.rectangle( x * tile_w, y * tile_h, x * tile_w + @intToFloat(f32, font.glyph_width), y * tile_h + @intToFloat(f32, font.glyph_height), ); } } try sprites.popCoord(); } try sprites.popCoord(); } glfwSwapBuffers(gfx_ctx.window); evs.poll(); } }
src/main.zig
const std = @import("std"); const c = @import("c.zig"); const utils = @import("utils.zig"); const intToError = @import("error.zig").intToError; const Error = @import("error.zig").Error; const Generic = @import("types.zig").Generic; pub const Library = @import("Library.zig"); pub const Face = @import("Face.zig"); pub const GlyphSlot = @import("GlyphSlot.zig"); pub const SizeRequest = c.FT_Size_RequestRec; pub const BitmapSize = c.FT_Bitmap_Size; pub const CharMap = c.FT_CharMapRec; pub const SizeMetrics = c.FT_Size_Metrics; pub const KerningMode = enum(u2) { default = c.FT_KERNING_DEFAULT, unfitted = c.FT_KERNING_UNFITTED, unscaled = c.FT_KERNING_UNSCALED, }; pub const RenderMode = enum(u3) { normal = c.FT_RENDER_MODE_NORMAL, light = c.FT_RENDER_MODE_LIGHT, mono = c.FT_RENDER_MODE_MONO, lcd = c.FT_RENDER_MODE_LCD, lcd_v = c.FT_RENDER_MODE_LCD_V, sdf = c.FT_RENDER_MODE_SDF, }; pub const SizeRequestType = enum(u3) { nominal = c.FT_SIZE_REQUEST_TYPE_NOMINAL, real_dim = c.FT_SIZE_REQUEST_TYPE_REAL_DIM, bbox = c.FT_SIZE_REQUEST_TYPE_BBOX, cell = c.FT_SIZE_REQUEST_TYPE_CELL, scales = c.FT_SIZE_REQUEST_TYPE_SCALES, max = c.FT_SIZE_REQUEST_TYPE_MAX, }; pub const Encoding = enum(u31) { none = c.FT_ENCODING_NONE, ms_symbol = c.FT_ENCODING_MS_SYMBOL, unicode = c.FT_ENCODING_UNICODE, sjis = c.FT_ENCODING_SJIS, prc = c.FT_ENCODING_PRC, big5 = c.FT_ENCODING_BIG5, wansung = c.FT_ENCODING_WANSUNG, johab = c.FT_ENCODING_JOHAB, adobe_standard = c.FT_ENCODING_ADOBE_STANDARD, adobe_expert = c.FT_ENCODING_ADOBE_EXPERT, adobe_custom = c.FT_ENCODING_ADOBE_CUSTOM, adobe_latin_1 = c.FT_ENCODING_ADOBE_LATIN_1, old_latin_2 = c.FT_ENCODING_OLD_LATIN_2, apple_roman = c.FT_ENCODING_APPLE_ROMAN, }; pub const Size = struct { handle: c.FT_Size, pub fn face(self: Size) Face { return Face{ .handle = self.handle.*.face }; } pub fn generic(self: Size) Generic { return self.handle.*.generic; } pub fn metrics(self: Size) SizeMetrics { return self.handle.*.metrics; } pub fn activate(self: Size) Error!void { try intToError(c.FT_Activate_Size(self.handle)); } pub fn deinit(self: Size) void { c.FT_Done_Size(self.handle); } }; pub const LoadFlags = packed struct { no_scale: bool = false, no_hinting: bool = false, render: bool = false, no_bitmap: bool = false, vertical_layout: bool = false, force_autohint: bool = false, crop_bitmap: bool = false, pedantic: bool = false, ignore_global_advance_with: bool = false, no_recurse: bool = false, ignore_transform: bool = false, monochrome: bool = false, linear_design: bool = false, no_autohint: bool = false, target_normal: bool = false, target_light: bool = false, target_mono: bool = false, target_lcd: bool = false, target_lcd_v: bool = false, color: bool = false, pub const Flag = enum(u21) { no_scale = c.FT_LOAD_NO_SCALE, no_hinting = c.FT_LOAD_NO_HINTING, render = c.FT_LOAD_RENDER, no_bitmap = c.FT_LOAD_NO_BITMAP, vertical_layout = c.FT_LOAD_VERTICAL_LAYOUT, force_autohint = c.FT_LOAD_FORCE_AUTOHINT, crop_bitmap = c.FT_LOAD_CROP_BITMAP, pedantic = c.FT_LOAD_PEDANTIC, ignore_global_advance_with = c.FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH, no_recurse = c.FT_LOAD_NO_RECURSE, ignore_transform = c.FT_LOAD_IGNORE_TRANSFORM, monochrome = c.FT_LOAD_MONOCHROME, linear_design = c.FT_LOAD_LINEAR_DESIGN, no_autohint = c.FT_LOAD_NO_AUTOHINT, target_normal = c.FT_LOAD_TARGET_NORMAL, target_light = c.FT_LOAD_TARGET_LIGHT, target_mono = c.FT_LOAD_TARGET_MONO, target_lcd = c.FT_LOAD_TARGET_LCD, target_lcd_v = c.FT_LOAD_TARGET_LCD_V, color = c.FT_LOAD_COLOR, }; pub fn from(bits: u21) LoadFlags { return utils.bitFieldsToStruct(LoadFlags, Flag, bits); } pub fn cast(flags: LoadFlags) u21 { return utils.structToBitFields(u21, Flag, flags); } }; pub const FaceFlags = packed struct { scalable: bool = false, fixed_sizes: bool = false, fixed_width: bool = false, sfnt: bool = false, horizontal: bool = false, vertical: bool = false, kerning: bool = false, fast_glyphs: bool = false, multiple_masters: bool = false, glyph_names: bool = false, external_stream: bool = false, hinter: bool = false, cid_keyed: bool = false, tricky: bool = false, color: bool = false, variation: bool = false, svg: bool = false, sbix: bool = false, sbix_overlay: bool = false, pub const Flag = enum(u19) { scalable = c.FT_FACE_FLAG_SCALABLE, fixed_sizes = c.FT_FACE_FLAG_FIXED_SIZES, fixed_width = c.FT_FACE_FLAG_FIXED_WIDTH, sfnt = c.FT_FACE_FLAG_SFNT, horizontal = c.FT_FACE_FLAG_HORIZONTAL, vertical = c.FT_FACE_FLAG_VERTICAL, kerning = c.FT_FACE_FLAG_KERNING, fast_glyphs = c.FT_FACE_FLAG_FAST_GLYPHS, multiple_masters = c.FT_FACE_FLAG_MULTIPLE_MASTERS, glyph_names = c.FT_FACE_FLAG_GLYPH_NAMES, external_stream = c.FT_FACE_FLAG_EXTERNAL_STREAM, hinter = c.FT_FACE_FLAG_HINTER, cid_keyed = c.FT_FACE_FLAG_CID_KEYED, tricky = c.FT_FACE_FLAG_TRICKY, color = c.FT_FACE_FLAG_COLOR, variation = c.FT_FACE_FLAG_VARIATION, svg = c.FT_FACE_FLAG_SVG, sbix = c.FT_FACE_FLAG_SBIX, sbix_overlay = c.FT_FACE_FLAG_SBIX_OVERLAY, }; pub fn from(bits: u19) FaceFlags { return utils.bitFieldsToStruct(FaceFlags, Flag, bits); } pub fn cast(self: FaceFlags) u19 { return utils.structToBitFields(u19, Flag, self); } }; pub const FSType = packed struct { installable_embedding: bool = false, restriced_license_embedding: bool = false, preview_and_print_embedding: bool = false, editable_embedding: bool = false, no_subsetting: bool = false, bitmap_embedding_only: bool = false, pub const Flag = enum(u10) { installable_embedding = c.FT_FSTYPE_INSTALLABLE_EMBEDDING, restriced_license_embedding = c.FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING, preview_and_print_embedding = c.FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING, editable_embedding = c.FT_FSTYPE_EDITABLE_EMBEDDING, no_subsetting = c.FT_FSTYPE_NO_SUBSETTING, bitmap_embedding_only = c.FT_FSTYPE_BITMAP_EMBEDDING_ONLY, }; pub fn from(bits: u10) FSType { return utils.bitFieldsToStruct(FSType, Flag, bits); } pub fn cast(flags: FSType) u10 { return utils.structToBitFields(u10, FSType, Flag, flags); } }; pub const StyleFlags = packed struct { italic: bool = false, bold: bool = false, pub const Flag = enum(u2) { italic = c.FT_STYLE_FLAG_ITALIC, bold = c.FT_STYLE_FLAG_BOLD, }; pub fn from(bits: u2) StyleFlags { return utils.bitFieldsToStruct(StyleFlags, Flag, bits); } pub fn cast(flags: StyleFlags) u2 { return utils.structToBitFields(u2, StyleFlags, Flag, flags); } }; pub const OpenFlags = packed struct { memory: bool = false, stream: bool = false, path: bool = false, driver: bool = false, params: bool = false, pub const Flag = enum(u5) { memory = c.FT_OPEN_MEMORY, stream = c.FT_OPEN_STREAM, path = c.FT_OPEN_PATHNAME, driver = c.FT_OPEN_DRIVER, params = c.FT_OPEN_PARAMS, }; pub fn from(bits: u5) OpenFlags { return utils.bitFieldsToStruct(OpenFlags, Flag, bits); } pub fn cast(flags: OpenFlags) u5 { return utils.structToBitFields(u5, Flag, flags); } }; pub const OpenArgs = struct { flags: OpenFlags, data: union(enum) { memory: []const u8, path: []const u8, stream: c.FT_Stream, driver: c.FT_Module, params: []const c.FT_Parameter, }, pub fn cast(self: OpenArgs) c.FT_Open_Args { var oa: c.FT_Open_Args = undefined; oa.flags = self.flags.cast(); switch (self.data) { .memory => |d| { oa.memory_base = d.ptr; oa.memory_size = @intCast(u31, d.len); }, .path => |*d| oa.pathname = @intToPtr(*u8, @ptrToInt(d.ptr)), .stream => |d| oa.stream = d, .driver => |d| oa.driver = d, .params => |*d| { oa.params = @intToPtr(*c.FT_Parameter, @ptrToInt(d.ptr)); oa.num_params = @intCast(u31, d.len); }, } return oa; } }; pub fn getCharmapIndex(self: [*c]CharMap) ?u32 { const i = c.FT_Get_Charmap_Index(self); return if (i == -1) null else @intCast(u32, i); }
freetype/src/freetype/freetype.zig
// These match the SunOS error numbering scheme. pub const EPERM = 1; pub const ENOENT = 2; pub const ESRCH = 3; pub const EINTR = 4; pub const EIO = 5; pub const ENXIO = 6; pub const E2BIG = 7; pub const ENOEXEC = 8; pub const EBADF = 9; pub const ECHILD = 10; pub const EAGAIN = 11; pub const ENOMEM = 12; pub const EACCES = 13; pub const EFAULT = 14; pub const ENOTBLK = 15; pub const EBUSY = 16; pub const EEXIST = 17; pub const EXDEV = 18; pub const ENODEV = 19; pub const ENOTDIR = 20; pub const EISDIR = 21; pub const EINVAL = 22; pub const ENFILE = 23; pub const EMFILE = 24; pub const ENOTTY = 25; pub const ETXTBSY = 26; pub const EFBIG = 27; pub const ENOSPC = 28; pub const ESPIPE = 29; pub const EROFS = 30; pub const EMLINK = 31; pub const EPIPE = 32; pub const EDOM = 33; pub const ERANGE = 34; pub const EWOULDBLOCK = EAGAIN; pub const EINPROGRESS = 36; pub const EALREADY = 37; pub const ENOTSOCK = 38; pub const EDESTADDRREQ = 39; pub const EMSGSIZE = 40; pub const EPROTOTYPE = 41; pub const ENOPROTOOPT = 42; pub const EPROTONOSUPPORT = 43; pub const ESOCKTNOSUPPORT = 44; pub const EOPNOTSUPP = 45; pub const EPFNOSUPPORT = 46; pub const EAFNOSUPPORT = 47; pub const EADDRINUSE = 48; pub const EADDRNOTAVAIL = 49; pub const ENETDOWN = 50; pub const ENETUNREACH = 51; pub const ENETRESET = 52; pub const ECONNABORTED = 53; pub const ECONNRESET = 54; pub const ENOBUFS = 55; pub const EISCONN = 56; pub const ENOTCONN = 57; pub const ESHUTDOWN = 58; pub const ETOOMANYREFS = 59; pub const ETIMEDOUT = 60; pub const ECONNREFUSED = 61; pub const ELOOP = 62; pub const ENAMETOOLONG = 63; pub const EHOSTDOWN = 64; pub const EHOSTUNREACH = 65; pub const ENOTEMPTY = 66; pub const EPROCLIM = 67; pub const EUSERS = 68; pub const EDQUOT = 69; pub const ESTALE = 70; pub const EREMOTE = 71; pub const ENOSTR = 72; pub const ETIME = 73; pub const ENOSR = 74; pub const ENOMSG = 75; pub const EBADMSG = 76; pub const EIDRM = 77; pub const EDEADLK = 78; pub const ENOLCK = 79; pub const ENONET = 80; pub const ERREMOTE = 81; pub const ENOLINK = 82; pub const EADV = 83; pub const ESRMNT = 84; pub const ECOMM = 85; pub const EPROTO = 86; pub const EMULTIHOP = 87; pub const EDOTDOT = 88; pub const EREMCHG = 89; pub const ENOSYS = 90; pub const ESTRPIPE = 91; pub const EOVERFLOW = 92; pub const EBADFD = 93; pub const ECHRNG = 94; pub const EL2NSYNC = 95; pub const EL3HLT = 96; pub const EL3RST = 97; pub const ELNRNG = 98; pub const EUNATCH = 99; pub const ENOCSI = 100; pub const EL2HLT = 101; pub const EBADE = 102; pub const EBADR = 103; pub const EXFULL = 104; pub const ENOANO = 105; pub const EBADRQC = 106; pub const EBADSLT = 107; pub const EDEADLOCK = 108; pub const EBFONT = 109; pub const ELIBEXEC = 110; pub const ENODATA = 111; pub const ELIBBAD = 112; pub const ENOPKG = 113; pub const ELIBACC = 114; pub const ENOTUNIQ = 115; pub const ERESTART = 116; pub const EUCLEAN = 117; pub const ENOTNAM = 118; pub const ENAVAIL = 119; pub const EISNAM = 120; pub const EREMOTEIO = 121; pub const EILSEQ = 122; pub const ELIBMAX = 123; pub const ELIBSCN = 124; pub const ENOMEDIUM = 125; pub const EMEDIUMTYPE = 126; pub const ECANCELED = 127; pub const ENOKEY = 128; pub const EKEYEXPIRED = 129; pub const EKEYREVOKED = 130; pub const EKEYREJECTED = 131; pub const EOWNERDEAD = 132; pub const ENOTRECOVERABLE = 133; pub const ERFKILL = 134; pub const EHWPOISON = 135;
lib/std/os/bits/linux/errno-sparc.zig
const ArrayList = std.ArrayList; const HeapAllocator = std.heap.HeapAllocator; const Image = zigimg.Image; const OctTreeQuantizer = zigimg.OctTreeQuantizer; const assert = std.debug.assert; const color = zigimg.color; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); usingnamespace @import("helpers.zig"); test "Build the oct tree with 3 colors" { var quantizer = OctTreeQuantizer.init(testing.allocator); defer quantizer.deinit(); const red = color.Color.initRGB(0xFF, 0, 0); const green = color.Color.initRGB(0, 0xFF, 0); const blue = color.Color.initRGB(0, 0, 0xFF); try quantizer.addColor(red); try quantizer.addColor(green); try quantizer.addColor(blue); var paletteStorage: [256]color.Color = undefined; var palette = try quantizer.makePalette(256, paletteStorage[0..]); expectEq(palette.len, 3); expectEq(try quantizer.getPaletteIndex(red), 2); expectEq(try quantizer.getPaletteIndex(green), 1); expectEq(try quantizer.getPaletteIndex(blue), 0); expectEq(palette[0].B, 0xFF); expectEq(palette[1].G, 0xFF); expectEq(palette[2].R, 0xFF); } test "Build a oct tree with 32-bit RGBA bitmap" { const MemoryRGBABitmap = @embedFile("fixtures/bmp/windows_rgba_v5.bmp"); var image = try Image.fromMemory(testing.allocator, MemoryRGBABitmap); defer image.deinit(); var quantizer = OctTreeQuantizer.init(testing.allocator); defer quantizer.deinit(); if (image.pixels) |pixelData| { // TODO: Use generic color iterator from Image for (pixelData.Argb32) |pixel| { try quantizer.addColor(pixel.toColor().premultipliedAlpha()); } } var paletteStorage: [256]color.Color = undefined; var palette = try quantizer.makePalette(255, paletteStorage[0..]); expectEq(palette.len, 255); var paletteIndex = try quantizer.getPaletteIndex(color.Color.initRGBA(110, 0, 0, 255)); expectEq(paletteIndex, 93); expectEq(palette[93].R, 110); expectEq(palette[93].G, 2); expectEq(palette[93].B, 2); expectEq(palette[93].A, 255); var secondPaletteIndex = try quantizer.getPaletteIndex(color.Color.initRGBA(0, 0, 119, 255)); expectEq(secondPaletteIndex, 53); expectEq(palette[53].R, 0); expectEq(palette[53].G, 0); expectEq(palette[53].B, 117); expectEq(palette[53].A, 255); }
tests/octree_quantizer_test.zig
const wchar_t = if (@import("builtin").os.tag == .windows) u16 else u32; pub extern fn SDL_GetPlatform() [*c]const u8; const struct_unnamed_1 = extern struct { __clang_max_align_nonce1: c_longlong align(8), __clang_max_align_nonce2: c_longdouble align(16), }; pub const SDL_FALSE = @enumToInt(enum_unnamed_2.SDL_FALSE); pub const SDL_TRUE = @enumToInt(enum_unnamed_2.SDL_TRUE); const enum_unnamed_2 = extern enum(c_int) { SDL_FALSE = 0, SDL_TRUE = 1, _, }; pub const SDL_bool = enum_unnamed_2; pub const DUMMY_ENUM_VALUE = @enumToInt(enum_unnamed_3.DUMMY_ENUM_VALUE); const enum_unnamed_3 = extern enum(c_int) { DUMMY_ENUM_VALUE, _, }; pub const SDL_DUMMY_ENUM = enum_unnamed_3; pub extern fn SDL_malloc(size: usize) ?*c_void; pub extern fn SDL_calloc(nmemb: usize, size: usize) ?*c_void; pub extern fn SDL_realloc(mem: ?*c_void, size: usize) ?*c_void; pub extern fn SDL_free(mem: ?*c_void) void; pub const SDL_malloc_func = ?fn (usize) callconv(.C) ?*c_void; pub const SDL_calloc_func = ?fn (usize, usize) callconv(.C) ?*c_void; pub const SDL_realloc_func = ?fn (?*c_void, usize) callconv(.C) ?*c_void; pub const SDL_free_func = ?fn (?*c_void) callconv(.C) void; pub extern fn SDL_GetMemoryFunctions(malloc_func: [*c]SDL_malloc_func, calloc_func: [*c]SDL_calloc_func, realloc_func: [*c]SDL_realloc_func, free_func: [*c]SDL_free_func) void; pub extern fn SDL_SetMemoryFunctions(malloc_func: SDL_malloc_func, calloc_func: SDL_calloc_func, realloc_func: SDL_realloc_func, free_func: SDL_free_func) c_int; pub extern fn SDL_GetNumAllocations() c_int; pub extern fn SDL_getenv(name: [*c]const u8) [*c]u8; pub extern fn SDL_setenv(name: [*c]const u8, value: [*c]const u8, overwrite: c_int) c_int; pub extern fn SDL_qsort(base: ?*c_void, nmemb: usize, size: usize, compare: ?fn (?*const c_void, ?*const c_void) callconv(.C) c_int) void; pub extern fn SDL_abs(x: c_int) c_int; pub extern fn SDL_isdigit(x: c_int) c_int; pub extern fn SDL_isspace(x: c_int) c_int; pub extern fn SDL_isupper(x: c_int) c_int; pub extern fn SDL_islower(x: c_int) c_int; pub extern fn SDL_toupper(x: c_int) c_int; pub extern fn SDL_tolower(x: c_int) c_int; pub extern fn SDL_crc32(crc: u32, data: ?*const c_void, len: usize) u32; pub extern fn SDL_memset(dst: ?*c_void, c: c_int, len: usize) ?*c_void; pub extern fn SDL_memcpy(dst: ?*c_void, src: ?*const c_void, len: usize) ?*c_void; pub extern fn SDL_memmove(dst: ?*c_void, src: ?*const c_void, len: usize) ?*c_void; pub extern fn SDL_memcmp(s1: ?*const c_void, s2: ?*const c_void, len: usize) c_int; pub extern fn SDL_wcslen(wstr: [*c]const wchar_t) usize; pub extern fn SDL_wcslcpy(dst: [*c]wchar_t, src: [*c]const wchar_t, maxlen: usize) usize; pub extern fn SDL_wcslcat(dst: [*c]wchar_t, src: [*c]const wchar_t, maxlen: usize) usize; pub extern fn SDL_wcsdup(wstr: [*c]const wchar_t) [*c]wchar_t; pub extern fn SDL_wcsstr(haystack: [*c]const wchar_t, needle: [*c]const wchar_t) [*c]wchar_t; pub extern fn SDL_wcscmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t) c_int; pub extern fn SDL_wcsncmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t, maxlen: usize) c_int; pub extern fn SDL_wcscasecmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t) c_int; pub extern fn SDL_wcsncasecmp(str1: [*c]const wchar_t, str2: [*c]const wchar_t, len: usize) c_int; pub extern fn SDL_strlen(str: [*c]const u8) usize; pub extern fn SDL_strlcpy(dst: [*c]u8, src: [*c]const u8, maxlen: usize) usize; pub extern fn SDL_utf8strlcpy(dst: [*c]u8, src: [*c]const u8, dst_bytes: usize) usize; pub extern fn SDL_strlcat(dst: [*c]u8, src: [*c]const u8, maxlen: usize) usize; pub extern fn SDL_strdup(str: [*c]const u8) [*c]u8; pub extern fn SDL_strrev(str: [*c]u8) [*c]u8; pub extern fn SDL_strupr(str: [*c]u8) [*c]u8; pub extern fn SDL_strlwr(str: [*c]u8) [*c]u8; pub extern fn SDL_strchr(str: [*c]const u8, c: c_int) [*c]u8; pub extern fn SDL_strrchr(str: [*c]const u8, c: c_int) [*c]u8; pub extern fn SDL_strstr(haystack: [*c]const u8, needle: [*c]const u8) [*c]u8; pub extern fn SDL_strtokr(s1: [*c]u8, s2: [*c]const u8, saveptr: [*c][*c]u8) [*c]u8; pub extern fn SDL_utf8strlen(str: [*c]const u8) usize; pub extern fn SDL_itoa(value: c_int, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_uitoa(value: c_uint, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_ltoa(value: c_long, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_ultoa(value: c_ulong, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_lltoa(value: i64, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_ulltoa(value: u64, str: [*c]u8, radix: c_int) [*c]u8; pub extern fn SDL_atoi(str: [*c]const u8) c_int; pub extern fn SDL_atof(str: [*c]const u8) f64; pub extern fn SDL_strtol(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) c_long; pub extern fn SDL_strtoul(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) c_ulong; pub extern fn SDL_strtoll(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) i64; pub extern fn SDL_strtoull(str: [*c]const u8, endp: [*c][*c]u8, base: c_int) u64; pub extern fn SDL_strtod(str: [*c]const u8, endp: [*c][*c]u8) f64; pub extern fn SDL_strcmp(str1: [*c]const u8, str2: [*c]const u8) c_int; pub extern fn SDL_strncmp(str1: [*c]const u8, str2: [*c]const u8, maxlen: usize) c_int; pub extern fn SDL_strcasecmp(str1: [*c]const u8, str2: [*c]const u8) c_int; pub extern fn SDL_strncasecmp(str1: [*c]const u8, str2: [*c]const u8, len: usize) c_int; pub extern fn SDL_sscanf(text: [*c]const u8, fmt: [*c]const u8, ...) c_int; pub const struct___va_list_tag = extern struct { gp_offset: c_uint, fp_offset: c_uint, overflow_arg_area: ?*c_void, reg_save_area: ?*c_void, }; pub extern fn SDL_vsscanf(text: [*c]const u8, fmt: [*c]const u8, ap: [*c]struct___va_list_tag) c_int; pub extern fn SDL_snprintf(text: [*c]u8, maxlen: usize, fmt: [*c]const u8, ...) c_int; pub extern fn SDL_vsnprintf(text: [*c]u8, maxlen: usize, fmt: [*c]const u8, ap: [*c]struct___va_list_tag) c_int; pub extern fn SDL_acos(x: f64) f64; pub extern fn SDL_acosf(x: f32) f32; pub extern fn SDL_asin(x: f64) f64; pub extern fn SDL_asinf(x: f32) f32; pub extern fn SDL_atan(x: f64) f64; pub extern fn SDL_atanf(x: f32) f32; pub extern fn SDL_atan2(x: f64, y: f64) f64; pub extern fn SDL_atan2f(x: f32, y: f32) f32; pub extern fn SDL_ceil(x: f64) f64; pub extern fn SDL_ceilf(x: f32) f32; pub extern fn SDL_copysign(x: f64, y: f64) f64; pub extern fn SDL_copysignf(x: f32, y: f32) f32; pub extern fn SDL_cos(x: f64) f64; pub extern fn SDL_cosf(x: f32) f32; pub extern fn SDL_exp(x: f64) f64; pub extern fn SDL_expf(x: f32) f32; pub extern fn SDL_fabs(x: f64) f64; pub extern fn SDL_fabsf(x: f32) f32; pub extern fn SDL_floor(x: f64) f64; pub extern fn SDL_floorf(x: f32) f32; pub extern fn SDL_trunc(x: f64) f64; pub extern fn SDL_truncf(x: f32) f32; pub extern fn SDL_fmod(x: f64, y: f64) f64; pub extern fn SDL_fmodf(x: f32, y: f32) f32; pub extern fn SDL_log(x: f64) f64; pub extern fn SDL_logf(x: f32) f32; pub extern fn SDL_log10(x: f64) f64; pub extern fn SDL_log10f(x: f32) f32; pub extern fn SDL_pow(x: f64, y: f64) f64; pub extern fn SDL_powf(x: f32, y: f32) f32; pub extern fn SDL_round(x: f64) f64; pub extern fn SDL_roundf(x: f32) f32; pub extern fn SDL_lround(x: f64) c_long; pub extern fn SDL_lroundf(x: f32) c_long; pub extern fn SDL_scalbn(x: f64, n: c_int) f64; pub extern fn SDL_scalbnf(x: f32, n: c_int) f32; pub extern fn SDL_sin(x: f64) f64; pub extern fn SDL_sinf(x: f32) f32; pub extern fn SDL_sqrt(x: f64) f64; pub extern fn SDL_sqrtf(x: f32) f32; pub extern fn SDL_tan(x: f64) f64; pub extern fn SDL_tanf(x: f32) f32; pub const struct__SDL_iconv_t = opaque {}; pub const SDL_iconv_t = ?*struct__SDL_iconv_t; pub extern fn SDL_iconv_open(tocode: [*c]const u8, fromcode: [*c]const u8) SDL_iconv_t; pub extern fn SDL_iconv_close(cd: SDL_iconv_t) c_int; pub extern fn SDL_iconv(cd: SDL_iconv_t, inbuf: [*c][*c]const u8, inbytesleft: [*c]usize, outbuf: [*c][*c]u8, outbytesleft: [*c]usize) usize; pub extern fn SDL_iconv_string(tocode: [*c]const u8, fromcode: [*c]const u8, inbuf: [*c]const u8, inbytesleft: usize) [*c]u8; pub fn SDL_memcpy4(arg_dst: ?*c_void, arg_src: ?*const c_void, arg_dwords: usize) callconv(.C) ?*c_void { var dst = arg_dst; var src = arg_src; var dwords = arg_dwords; return SDL_memcpy(dst, src, (dwords *% @bitCast(c_ulong, @as(c_long, @as(c_int, 4))))); } pub const SDL_main_func = ?fn (c_int, [*c][*c]u8) callconv(.C) c_int; pub extern fn SDL_main(argc: c_int, argv: [*c][*c]u8) c_int; pub extern fn SDL_SetMainReady() void; pub const SDL_ASSERTION_RETRY = @enumToInt(enum_unnamed_4.SDL_ASSERTION_RETRY); pub const SDL_ASSERTION_BREAK = @enumToInt(enum_unnamed_4.SDL_ASSERTION_BREAK); pub const SDL_ASSERTION_ABORT = @enumToInt(enum_unnamed_4.SDL_ASSERTION_ABORT); pub const SDL_ASSERTION_IGNORE = @enumToInt(enum_unnamed_4.SDL_ASSERTION_IGNORE); pub const SDL_ASSERTION_ALWAYS_IGNORE = @enumToInt(enum_unnamed_4.SDL_ASSERTION_ALWAYS_IGNORE); const enum_unnamed_4 = extern enum(c_int) { SDL_ASSERTION_RETRY, SDL_ASSERTION_BREAK, SDL_ASSERTION_ABORT, SDL_ASSERTION_IGNORE, SDL_ASSERTION_ALWAYS_IGNORE, _, }; pub const SDL_AssertState = enum_unnamed_4; pub const struct_SDL_AssertData = extern struct { always_ignore: c_int, trigger_count: c_uint, condition: [*c]const u8, filename: [*c]const u8, linenum: c_int, function: [*c]const u8, next: [*c]const struct_SDL_AssertData, }; pub const SDL_AssertData = struct_SDL_AssertData; pub extern fn SDL_ReportAssertion([*c]SDL_AssertData, [*c]const u8, [*c]const u8, c_int) SDL_AssertState; pub const SDL_AssertionHandler = ?fn ([*c]const SDL_AssertData, ?*c_void) callconv(.C) SDL_AssertState; pub extern fn SDL_SetAssertionHandler(handler: SDL_AssertionHandler, userdata: ?*c_void) void; pub extern fn SDL_GetDefaultAssertionHandler() SDL_AssertionHandler; pub extern fn SDL_GetAssertionHandler(puserdata: [*c]?*c_void) SDL_AssertionHandler; pub extern fn SDL_GetAssertionReport() [*c]const SDL_AssertData; pub extern fn SDL_ResetAssertionReport() void; pub const SDL_SpinLock = c_int; pub extern fn SDL_AtomicTryLock(lock: [*c]SDL_SpinLock) SDL_bool; pub extern fn SDL_AtomicLock(lock: [*c]SDL_SpinLock) void; pub extern fn SDL_AtomicUnlock(lock: [*c]SDL_SpinLock) void; pub extern fn SDL_MemoryBarrierReleaseFunction() void; pub extern fn SDL_MemoryBarrierAcquireFunction() void; const struct_unnamed_5 = extern struct { value: c_int, }; pub const SDL_atomic_t = struct_unnamed_5; pub extern fn SDL_AtomicCAS(a: [*c]SDL_atomic_t, oldval: c_int, newval: c_int) SDL_bool; pub extern fn SDL_AtomicSet(a: [*c]SDL_atomic_t, v: c_int) c_int; pub extern fn SDL_AtomicGet(a: [*c]SDL_atomic_t) c_int; pub extern fn SDL_AtomicAdd(a: [*c]SDL_atomic_t, v: c_int) c_int; pub extern fn SDL_AtomicCASPtr(a: [*c]?*c_void, oldval: ?*c_void, newval: ?*c_void) SDL_bool; pub extern fn SDL_AtomicSetPtr(a: [*c]?*c_void, v: ?*c_void) ?*c_void; pub extern fn SDL_AtomicGetPtr(a: [*c]?*c_void) ?*c_void; pub extern fn SDL_SetError(fmt: [*c]const u8, ...) c_int; pub extern fn SDL_GetError() [*c]const u8; pub extern fn SDL_GetErrorMsg(errstr: [*c]u8, maxlen: c_int) [*c]u8; pub extern fn SDL_ClearError() void; pub const SDL_ENOMEM = @enumToInt(enum_unnamed_6.SDL_ENOMEM); pub const SDL_EFREAD = @enumToInt(enum_unnamed_6.SDL_EFREAD); pub const SDL_EFWRITE = @enumToInt(enum_unnamed_6.SDL_EFWRITE); pub const SDL_EFSEEK = @enumToInt(enum_unnamed_6.SDL_EFSEEK); pub const SDL_UNSUPPORTED = @enumToInt(enum_unnamed_6.SDL_UNSUPPORTED); pub const SDL_LASTERROR = @enumToInt(enum_unnamed_6.SDL_LASTERROR); const enum_unnamed_6 = extern enum(c_int) { SDL_ENOMEM, SDL_EFREAD, SDL_EFWRITE, SDL_EFSEEK, SDL_UNSUPPORTED, SDL_LASTERROR, _, }; pub const SDL_errorcode = enum_unnamed_6; pub extern fn SDL_Error(code: SDL_errorcode) c_int; pub const struct_SDL_mutex = opaque {}; pub const SDL_mutex = struct_SDL_mutex; pub extern fn SDL_CreateMutex() ?*SDL_mutex; pub extern fn SDL_LockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_TryLockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_UnlockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_DestroyMutex(mutex: ?*SDL_mutex) void; pub const struct_SDL_semaphore = opaque {}; pub const SDL_sem = struct_SDL_semaphore; pub extern fn SDL_CreateSemaphore(initial_value: u32) ?*SDL_sem; pub extern fn SDL_DestroySemaphore(sem: ?*SDL_sem) void; pub extern fn SDL_SemWait(sem: ?*SDL_sem) c_int; pub extern fn SDL_SemTryWait(sem: ?*SDL_sem) c_int; pub extern fn SDL_SemWaitTimeout(sem: ?*SDL_sem, ms: u32) c_int; pub extern fn SDL_SemPost(sem: ?*SDL_sem) c_int; pub extern fn SDL_SemValue(sem: ?*SDL_sem) u32; pub const struct_SDL_cond = opaque {}; pub const SDL_cond = struct_SDL_cond; pub extern fn SDL_CreateCond() ?*SDL_cond; pub extern fn SDL_DestroyCond(cond: ?*SDL_cond) void; pub extern fn SDL_CondSignal(cond: ?*SDL_cond) c_int; pub extern fn SDL_CondBroadcast(cond: ?*SDL_cond) c_int; pub extern fn SDL_CondWait(cond: ?*SDL_cond, mutex: ?*SDL_mutex) c_int; pub extern fn SDL_CondWaitTimeout(cond: ?*SDL_cond, mutex: ?*SDL_mutex, ms: u32) c_int; pub const struct_SDL_Thread = opaque {}; pub const SDL_Thread = struct_SDL_Thread; pub const SDL_threadID = c_ulong; pub const SDL_TLSID = c_uint; pub const SDL_THREAD_PRIORITY_LOW = @enumToInt(enum_unnamed_7.SDL_THREAD_PRIORITY_LOW); pub const SDL_THREAD_PRIORITY_NORMAL = @enumToInt(enum_unnamed_7.SDL_THREAD_PRIORITY_NORMAL); pub const SDL_THREAD_PRIORITY_HIGH = @enumToInt(enum_unnamed_7.SDL_THREAD_PRIORITY_HIGH); pub const SDL_THREAD_PRIORITY_TIME_CRITICAL = @enumToInt(enum_unnamed_7.SDL_THREAD_PRIORITY_TIME_CRITICAL); const enum_unnamed_7 = extern enum(c_int) { SDL_THREAD_PRIORITY_LOW, SDL_THREAD_PRIORITY_NORMAL, SDL_THREAD_PRIORITY_HIGH, SDL_THREAD_PRIORITY_TIME_CRITICAL, _, }; pub const SDL_ThreadPriority = enum_unnamed_7; pub const SDL_ThreadFunction = ?fn (?*c_void) callconv(.C) c_int; pub extern fn SDL_CreateThread(@"fn": SDL_ThreadFunction, name: [*c]const u8, data: ?*c_void) ?*SDL_Thread; pub extern fn SDL_CreateThreadWithStackSize(@"fn": SDL_ThreadFunction, name: [*c]const u8, stacksize: usize, data: ?*c_void) ?*SDL_Thread; pub extern fn SDL_GetThreadName(thread: ?*SDL_Thread) [*c]const u8; pub extern fn SDL_ThreadID() SDL_threadID; pub extern fn SDL_GetThreadID(thread: ?*SDL_Thread) SDL_threadID; pub extern fn SDL_SetThreadPriority(priority: SDL_ThreadPriority) c_int; pub extern fn SDL_WaitThread(thread: ?*SDL_Thread, status: [*c]c_int) void; pub extern fn SDL_DetachThread(thread: ?*SDL_Thread) void; pub extern fn SDL_TLSCreate() SDL_TLSID; pub extern fn SDL_TLSGet(id: SDL_TLSID) ?*c_void; pub extern fn SDL_TLSSet(id: SDL_TLSID, value: ?*const c_void, destructor: ?fn (?*c_void) callconv(.C) void) c_int; const struct_unnamed_9 = extern struct { base: [*c]u8, here: [*c]u8, stop: [*c]u8, }; const struct_unnamed_10 = extern struct { data1: ?*c_void, data2: ?*c_void, }; const union_unnamed_8 = extern union { mem: struct_unnamed_9, unknown: struct_unnamed_10, }; pub const struct_SDL_RWops = extern struct { size: ?fn ([*c]struct_SDL_RWops) callconv(.C) i64, seek: ?fn ([*c]struct_SDL_RWops, i64, c_int) callconv(.C) i64, read: ?fn ([*c]struct_SDL_RWops, ?*c_void, usize, usize) callconv(.C) usize, write: ?fn ([*c]struct_SDL_RWops, ?*const c_void, usize, usize) callconv(.C) usize, close: ?fn ([*c]struct_SDL_RWops) callconv(.C) c_int, type: u32, hidden: union_unnamed_8, }; pub const SDL_RWops = struct_SDL_RWops; pub extern fn SDL_RWFromFile(file: [*c]const u8, mode: [*c]const u8) [*c]SDL_RWops; pub extern fn SDL_RWFromFP(fp: ?*c_void, autoclose: SDL_bool) [*c]SDL_RWops; pub extern fn SDL_RWFromMem(mem: ?*c_void, size: c_int) [*c]SDL_RWops; pub extern fn SDL_RWFromConstMem(mem: ?*const c_void, size: c_int) [*c]SDL_RWops; pub extern fn SDL_AllocRW() [*c]SDL_RWops; pub extern fn SDL_FreeRW(area: [*c]SDL_RWops) void; pub extern fn SDL_RWsize(context: [*c]SDL_RWops) i64; pub extern fn SDL_RWseek(context: [*c]SDL_RWops, offset: i64, whence: c_int) i64; pub extern fn SDL_RWtell(context: [*c]SDL_RWops) i64; pub extern fn SDL_RWread(context: [*c]SDL_RWops, ptr: ?*c_void, size: usize, maxnum: usize) usize; pub extern fn SDL_RWwrite(context: [*c]SDL_RWops, ptr: ?*const c_void, size: usize, num: usize) usize; pub extern fn SDL_RWclose(context: [*c]SDL_RWops) c_int; pub extern fn SDL_LoadFile_RW(src: [*c]SDL_RWops, datasize: [*c]usize, freesrc: c_int) ?*c_void; pub extern fn SDL_LoadFile(file: [*c]const u8, datasize: [*c]usize) ?*c_void; pub extern fn SDL_ReadU8(src: [*c]SDL_RWops) u8; pub extern fn SDL_ReadLE16(src: [*c]SDL_RWops) u16; pub extern fn SDL_ReadBE16(src: [*c]SDL_RWops) u16; pub extern fn SDL_ReadLE32(src: [*c]SDL_RWops) u32; pub extern fn SDL_ReadBE32(src: [*c]SDL_RWops) u32; pub extern fn SDL_ReadLE64(src: [*c]SDL_RWops) u64; pub extern fn SDL_ReadBE64(src: [*c]SDL_RWops) u64; pub extern fn SDL_WriteU8(dst: [*c]SDL_RWops, value: u8) usize; pub extern fn SDL_WriteLE16(dst: [*c]SDL_RWops, value: u16) usize; pub extern fn SDL_WriteBE16(dst: [*c]SDL_RWops, value: u16) usize; pub extern fn SDL_WriteLE32(dst: [*c]SDL_RWops, value: u32) usize; pub extern fn SDL_WriteBE32(dst: [*c]SDL_RWops, value: u32) usize; pub extern fn SDL_WriteLE64(dst: [*c]SDL_RWops, value: u64) usize; pub extern fn SDL_WriteBE64(dst: [*c]SDL_RWops, value: u64) usize; pub const SDL_AudioFormat = u16; pub const SDL_AudioCallback = ?fn (?*c_void, [*c]u8, c_int) callconv(.C) void; pub const struct_SDL_AudioSpec = extern struct { freq: c_int, format: SDL_AudioFormat, channels: u8, silence: u8, samples: u16, padding: u16, size: u32, callback: SDL_AudioCallback, userdata: ?*c_void, }; pub const SDL_AudioSpec = struct_SDL_AudioSpec; pub const struct_SDL_AudioCVT = extern struct { needed: c_int, src_format: SDL_AudioFormat, dst_format: SDL_AudioFormat, rate_incr: f64, buf: [*c]u8, len: c_int, len_cvt: c_int, len_mult: c_int, len_ratio: f64, filters: [10]SDL_AudioFilter, filter_index: c_int, }; pub const SDL_AudioFilter = ?fn ([*c]struct_SDL_AudioCVT, SDL_AudioFormat) callconv(.C) void; pub const SDL_AudioCVT = struct_SDL_AudioCVT; pub extern fn SDL_GetNumAudioDrivers() c_int; pub extern fn SDL_GetAudioDriver(index: c_int) [*c]const u8; pub extern fn SDL_AudioInit(driver_name: [*c]const u8) c_int; pub extern fn SDL_AudioQuit() void; pub extern fn SDL_GetCurrentAudioDriver() [*c]const u8; pub extern fn SDL_OpenAudio(desired: [*c]SDL_AudioSpec, obtained: [*c]SDL_AudioSpec) c_int; pub const SDL_AudioDeviceID = u32; pub extern fn SDL_GetNumAudioDevices(iscapture: c_int) c_int; pub extern fn SDL_GetAudioDeviceName(index: c_int, iscapture: c_int) [*c]const u8; pub extern fn SDL_OpenAudioDevice(device: [*c]const u8, iscapture: c_int, desired: [*c]const SDL_AudioSpec, obtained: [*c]SDL_AudioSpec, allowed_changes: c_int) SDL_AudioDeviceID; pub const SDL_AUDIO_STOPPED = @enumToInt(enum_unnamed_11.SDL_AUDIO_STOPPED); pub const SDL_AUDIO_PLAYING = @enumToInt(enum_unnamed_11.SDL_AUDIO_PLAYING); pub const SDL_AUDIO_PAUSED = @enumToInt(enum_unnamed_11.SDL_AUDIO_PAUSED); const enum_unnamed_11 = extern enum(c_int) { SDL_AUDIO_STOPPED = 0, SDL_AUDIO_PLAYING = 1, SDL_AUDIO_PAUSED = 2, _, }; pub const SDL_AudioStatus = enum_unnamed_11; pub extern fn SDL_GetAudioStatus() SDL_AudioStatus; pub extern fn SDL_GetAudioDeviceStatus(dev: SDL_AudioDeviceID) SDL_AudioStatus; pub extern fn SDL_PauseAudio(pause_on: c_int) void; pub extern fn SDL_PauseAudioDevice(dev: SDL_AudioDeviceID, pause_on: c_int) void; pub extern fn SDL_LoadWAV_RW(src: [*c]SDL_RWops, freesrc: c_int, spec: [*c]SDL_AudioSpec, audio_buf: [*c][*c]u8, audio_len: [*c]u32) [*c]SDL_AudioSpec; pub extern fn SDL_FreeWAV(audio_buf: [*c]u8) void; pub extern fn SDL_BuildAudioCVT(cvt: [*c]SDL_AudioCVT, src_format: SDL_AudioFormat, src_channels: u8, src_rate: c_int, dst_format: SDL_AudioFormat, dst_channels: u8, dst_rate: c_int) c_int; pub extern fn SDL_ConvertAudio(cvt: [*c]SDL_AudioCVT) c_int; pub const struct__SDL_AudioStream = opaque {}; pub const SDL_AudioStream = struct__SDL_AudioStream; pub extern fn SDL_NewAudioStream(src_format: SDL_AudioFormat, src_channels: u8, src_rate: c_int, dst_format: SDL_AudioFormat, dst_channels: u8, dst_rate: c_int) ?*SDL_AudioStream; pub extern fn SDL_AudioStreamPut(stream: ?*SDL_AudioStream, buf: ?*const c_void, len: c_int) c_int; pub extern fn SDL_AudioStreamGet(stream: ?*SDL_AudioStream, buf: ?*c_void, len: c_int) c_int; pub extern fn SDL_AudioStreamAvailable(stream: ?*SDL_AudioStream) c_int; pub extern fn SDL_AudioStreamFlush(stream: ?*SDL_AudioStream) c_int; pub extern fn SDL_AudioStreamClear(stream: ?*SDL_AudioStream) void; pub extern fn SDL_FreeAudioStream(stream: ?*SDL_AudioStream) void; pub extern fn SDL_MixAudio(dst: [*c]u8, src: [*c]const u8, len: u32, volume: c_int) void; pub extern fn SDL_MixAudioFormat(dst: [*c]u8, src: [*c]const u8, format: SDL_AudioFormat, len: u32, volume: c_int) void; pub extern fn SDL_QueueAudio(dev: SDL_AudioDeviceID, data: ?*const c_void, len: u32) c_int; pub extern fn SDL_DequeueAudio(dev: SDL_AudioDeviceID, data: ?*c_void, len: u32) u32; pub extern fn SDL_GetQueuedAudioSize(dev: SDL_AudioDeviceID) u32; pub extern fn SDL_ClearQueuedAudio(dev: SDL_AudioDeviceID) void; pub extern fn SDL_LockAudio() void; pub extern fn SDL_LockAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_UnlockAudio() void; pub extern fn SDL_UnlockAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_CloseAudio() void; pub extern fn SDL_CloseAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_SetClipboardText(text: [*c]const u8) c_int; pub extern fn SDL_GetClipboardText() [*c]u8; pub extern fn SDL_HasClipboardText() SDL_bool; pub extern fn SDL_GetCPUCount() c_int; pub extern fn SDL_GetCPUCacheLineSize() c_int; pub extern fn SDL_HasRDTSC() SDL_bool; pub extern fn SDL_HasAltiVec() SDL_bool; pub extern fn SDL_HasMMX() SDL_bool; pub extern fn SDL_Has3DNow() SDL_bool; pub extern fn SDL_HasSSE() SDL_bool; pub extern fn SDL_HasSSE2() SDL_bool; pub extern fn SDL_HasSSE3() SDL_bool; pub extern fn SDL_HasSSE41() SDL_bool; pub extern fn SDL_HasSSE42() SDL_bool; pub extern fn SDL_HasAVX() SDL_bool; pub extern fn SDL_HasAVX2() SDL_bool; pub extern fn SDL_HasAVX512F() SDL_bool; pub extern fn SDL_HasARMSIMD() SDL_bool; pub extern fn SDL_HasNEON() SDL_bool; pub extern fn SDL_GetSystemRAM() c_int; pub extern fn SDL_SIMDGetAlignment() usize; pub extern fn SDL_SIMDAlloc(len: usize) ?*c_void; pub extern fn SDL_SIMDRealloc(mem: ?*c_void, len: usize) ?*c_void; pub extern fn SDL_SIMDFree(ptr: ?*c_void) void; pub const SDL_PIXELTYPE_UNKNOWN = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_UNKNOWN); pub const SDL_PIXELTYPE_INDEX1 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_INDEX1); pub const SDL_PIXELTYPE_INDEX4 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_INDEX4); pub const SDL_PIXELTYPE_INDEX8 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_INDEX8); pub const SDL_PIXELTYPE_PACKED8 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_PACKED8); pub const SDL_PIXELTYPE_PACKED16 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_PACKED16); pub const SDL_PIXELTYPE_PACKED32 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_PACKED32); pub const SDL_PIXELTYPE_ARRAYU8 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_ARRAYU8); pub const SDL_PIXELTYPE_ARRAYU16 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_ARRAYU16); pub const SDL_PIXELTYPE_ARRAYU32 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_ARRAYU32); pub const SDL_PIXELTYPE_ARRAYF16 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_ARRAYF16); pub const SDL_PIXELTYPE_ARRAYF32 = @enumToInt(enum_unnamed_12.SDL_PIXELTYPE_ARRAYF32); const enum_unnamed_12 = extern enum(c_int) { SDL_PIXELTYPE_UNKNOWN, SDL_PIXELTYPE_INDEX1, SDL_PIXELTYPE_INDEX4, SDL_PIXELTYPE_INDEX8, SDL_PIXELTYPE_PACKED8, SDL_PIXELTYPE_PACKED16, SDL_PIXELTYPE_PACKED32, SDL_PIXELTYPE_ARRAYU8, SDL_PIXELTYPE_ARRAYU16, SDL_PIXELTYPE_ARRAYU32, SDL_PIXELTYPE_ARRAYF16, SDL_PIXELTYPE_ARRAYF32, _, }; pub const SDL_PixelType = enum_unnamed_12; pub const SDL_BITMAPORDER_NONE = @enumToInt(enum_unnamed_13.SDL_BITMAPORDER_NONE); pub const SDL_BITMAPORDER_4321 = @enumToInt(enum_unnamed_13.SDL_BITMAPORDER_4321); pub const SDL_BITMAPORDER_1234 = @enumToInt(enum_unnamed_13.SDL_BITMAPORDER_1234); const enum_unnamed_13 = extern enum(c_int) { SDL_BITMAPORDER_NONE, SDL_BITMAPORDER_4321, SDL_BITMAPORDER_1234, _, }; pub const SDL_BitmapOrder = enum_unnamed_13; pub const SDL_PACKEDORDER_NONE = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_NONE); pub const SDL_PACKEDORDER_XRGB = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_XRGB); pub const SDL_PACKEDORDER_RGBX = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_RGBX); pub const SDL_PACKEDORDER_ARGB = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_ARGB); pub const SDL_PACKEDORDER_RGBA = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_RGBA); pub const SDL_PACKEDORDER_XBGR = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_XBGR); pub const SDL_PACKEDORDER_BGRX = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_BGRX); pub const SDL_PACKEDORDER_ABGR = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_ABGR); pub const SDL_PACKEDORDER_BGRA = @enumToInt(enum_unnamed_14.SDL_PACKEDORDER_BGRA); const enum_unnamed_14 = extern enum(c_int) { SDL_PACKEDORDER_NONE, SDL_PACKEDORDER_XRGB, SDL_PACKEDORDER_RGBX, SDL_PACKEDORDER_ARGB, SDL_PACKEDORDER_RGBA, SDL_PACKEDORDER_XBGR, SDL_PACKEDORDER_BGRX, SDL_PACKEDORDER_ABGR, SDL_PACKEDORDER_BGRA, _, }; pub const SDL_PackedOrder = enum_unnamed_14; pub const SDL_ARRAYORDER_NONE = @enumToInt(enum_unnamed_15.SDL_ARRAYORDER_NONE); pub const SDL_ARRAYORDER_RGB = @enumToInt(enum_unnamed_15.SDL_ARRAYORDER_RGB); pub const SDL_ARRAYORDER_RGBA = @enumToInt(enum_unnamed_15.SDL_ARRAYORDER_RGBA); pub const SDL_ARRAYORDER_ARGB = @enumToInt(enum_unnamed_15.SDL_ARRAYORDER_ARGB); pub const SDL_ARRAYORDER_BGR = @enumToInt(enum_unnamed_15.SDL_ARRAYORDER_BGR); pub const SDL_ARRAYORDER_BGRA = @enumToInt(enum_unnamed_15.SDL_ARRAYORDER_BGRA); pub const SDL_ARRAYORDER_ABGR = @enumToInt(enum_unnamed_15.SDL_ARRAYORDER_ABGR); const enum_unnamed_15 = extern enum(c_int) { SDL_ARRAYORDER_NONE, SDL_ARRAYORDER_RGB, SDL_ARRAYORDER_RGBA, SDL_ARRAYORDER_ARGB, SDL_ARRAYORDER_BGR, SDL_ARRAYORDER_BGRA, SDL_ARRAYORDER_ABGR, _, }; pub const SDL_ArrayOrder = enum_unnamed_15; pub const SDL_PACKEDLAYOUT_NONE = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_NONE); pub const SDL_PACKEDLAYOUT_332 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_332); pub const SDL_PACKEDLAYOUT_4444 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_4444); pub const SDL_PACKEDLAYOUT_1555 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_1555); pub const SDL_PACKEDLAYOUT_5551 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_5551); pub const SDL_PACKEDLAYOUT_565 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_565); pub const SDL_PACKEDLAYOUT_8888 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_8888); pub const SDL_PACKEDLAYOUT_2101010 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_2101010); pub const SDL_PACKEDLAYOUT_1010102 = @enumToInt(enum_unnamed_16.SDL_PACKEDLAYOUT_1010102); const enum_unnamed_16 = extern enum(c_int) { SDL_PACKEDLAYOUT_NONE, SDL_PACKEDLAYOUT_332, SDL_PACKEDLAYOUT_4444, SDL_PACKEDLAYOUT_1555, SDL_PACKEDLAYOUT_5551, SDL_PACKEDLAYOUT_565, SDL_PACKEDLAYOUT_8888, SDL_PACKEDLAYOUT_2101010, SDL_PACKEDLAYOUT_1010102, _, }; pub const SDL_PackedLayout = enum_unnamed_16; pub const SDL_PIXELFORMAT_UNKNOWN = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_UNKNOWN); pub const SDL_PIXELFORMAT_INDEX1LSB = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_INDEX1LSB); pub const SDL_PIXELFORMAT_INDEX1MSB = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_INDEX1MSB); pub const SDL_PIXELFORMAT_INDEX4LSB = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_INDEX4LSB); pub const SDL_PIXELFORMAT_INDEX4MSB = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_INDEX4MSB); pub const SDL_PIXELFORMAT_INDEX8 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_INDEX8); pub const SDL_PIXELFORMAT_RGB332 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGB332); pub const SDL_PIXELFORMAT_XRGB4444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_XRGB4444); pub const SDL_PIXELFORMAT_RGB444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGB444); pub const SDL_PIXELFORMAT_XBGR4444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_XBGR4444); pub const SDL_PIXELFORMAT_BGR444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGR444); pub const SDL_PIXELFORMAT_XRGB1555 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_XRGB1555); pub const SDL_PIXELFORMAT_RGB555 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGB555); pub const SDL_PIXELFORMAT_XBGR1555 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_XBGR1555); pub const SDL_PIXELFORMAT_BGR555 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGR555); pub const SDL_PIXELFORMAT_ARGB4444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ARGB4444); pub const SDL_PIXELFORMAT_RGBA4444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGBA4444); pub const SDL_PIXELFORMAT_ABGR4444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ABGR4444); pub const SDL_PIXELFORMAT_BGRA4444 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGRA4444); pub const SDL_PIXELFORMAT_ARGB1555 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ARGB1555); pub const SDL_PIXELFORMAT_RGBA5551 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGBA5551); pub const SDL_PIXELFORMAT_ABGR1555 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ABGR1555); pub const SDL_PIXELFORMAT_BGRA5551 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGRA5551); pub const SDL_PIXELFORMAT_RGB565 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGB565); pub const SDL_PIXELFORMAT_BGR565 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGR565); pub const SDL_PIXELFORMAT_RGB24 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGB24); pub const SDL_PIXELFORMAT_BGR24 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGR24); pub const SDL_PIXELFORMAT_XRGB8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_XRGB8888); pub const SDL_PIXELFORMAT_RGB888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGB888); pub const SDL_PIXELFORMAT_RGBX8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGBX8888); pub const SDL_PIXELFORMAT_XBGR8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_XBGR8888); pub const SDL_PIXELFORMAT_BGR888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGR888); pub const SDL_PIXELFORMAT_BGRX8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGRX8888); pub const SDL_PIXELFORMAT_ARGB8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ARGB8888); pub const SDL_PIXELFORMAT_RGBA8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGBA8888); pub const SDL_PIXELFORMAT_ABGR8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ABGR8888); pub const SDL_PIXELFORMAT_BGRA8888 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGRA8888); pub const SDL_PIXELFORMAT_ARGB2101010 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ARGB2101010); pub const SDL_PIXELFORMAT_RGBA32 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_RGBA32); pub const SDL_PIXELFORMAT_ARGB32 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ARGB32); pub const SDL_PIXELFORMAT_BGRA32 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_BGRA32); pub const SDL_PIXELFORMAT_ABGR32 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_ABGR32); pub const SDL_PIXELFORMAT_YV12 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_YV12); pub const SDL_PIXELFORMAT_IYUV = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_IYUV); pub const SDL_PIXELFORMAT_YUY2 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_YUY2); pub const SDL_PIXELFORMAT_UYVY = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_UYVY); pub const SDL_PIXELFORMAT_YVYU = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_YVYU); pub const SDL_PIXELFORMAT_NV12 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_NV12); pub const SDL_PIXELFORMAT_NV21 = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_NV21); pub const SDL_PIXELFORMAT_EXTERNAL_OES = @enumToInt(enum_unnamed_17.SDL_PIXELFORMAT_EXTERNAL_OES); const enum_unnamed_17 = extern enum(c_int) { SDL_PIXELFORMAT_UNKNOWN = 0, SDL_PIXELFORMAT_INDEX1LSB = 286261504, SDL_PIXELFORMAT_INDEX1MSB = 287310080, SDL_PIXELFORMAT_INDEX4LSB = 303039488, SDL_PIXELFORMAT_INDEX4MSB = 304088064, SDL_PIXELFORMAT_INDEX8 = 318769153, SDL_PIXELFORMAT_RGB332 = 336660481, SDL_PIXELFORMAT_XRGB4444 = 353504258, SDL_PIXELFORMAT_RGB444 = 353504258, SDL_PIXELFORMAT_XBGR4444 = 357698562, SDL_PIXELFORMAT_BGR444 = 357698562, SDL_PIXELFORMAT_XRGB1555 = 353570562, SDL_PIXELFORMAT_RGB555 = 353570562, SDL_PIXELFORMAT_XBGR1555 = 357764866, SDL_PIXELFORMAT_BGR555 = 357764866, SDL_PIXELFORMAT_ARGB4444 = 355602434, SDL_PIXELFORMAT_RGBA4444 = 356651010, SDL_PIXELFORMAT_ABGR4444 = 359796738, SDL_PIXELFORMAT_BGRA4444 = 360845314, SDL_PIXELFORMAT_ARGB1555 = 355667970, SDL_PIXELFORMAT_RGBA5551 = 356782082, SDL_PIXELFORMAT_ABGR1555 = 359862274, SDL_PIXELFORMAT_BGRA5551 = 360976386, SDL_PIXELFORMAT_RGB565 = 353701890, SDL_PIXELFORMAT_BGR565 = 357896194, SDL_PIXELFORMAT_RGB24 = 386930691, SDL_PIXELFORMAT_BGR24 = 390076419, SDL_PIXELFORMAT_XRGB8888 = 370546692, SDL_PIXELFORMAT_RGB888 = 370546692, SDL_PIXELFORMAT_RGBX8888 = 371595268, SDL_PIXELFORMAT_XBGR8888 = 374740996, SDL_PIXELFORMAT_BGR888 = 374740996, SDL_PIXELFORMAT_BGRX8888 = 375789572, SDL_PIXELFORMAT_ARGB8888 = 372645892, SDL_PIXELFORMAT_RGBA8888 = 373694468, SDL_PIXELFORMAT_ABGR8888 = 376840196, SDL_PIXELFORMAT_BGRA8888 = 377888772, SDL_PIXELFORMAT_ARGB2101010 = 372711428, SDL_PIXELFORMAT_RGBA32 = 376840196, SDL_PIXELFORMAT_ARGB32 = 377888772, SDL_PIXELFORMAT_BGRA32 = 372645892, SDL_PIXELFORMAT_ABGR32 = 373694468, SDL_PIXELFORMAT_YV12 = 842094169, SDL_PIXELFORMAT_IYUV = 1448433993, SDL_PIXELFORMAT_YUY2 = 844715353, SDL_PIXELFORMAT_UYVY = 1498831189, SDL_PIXELFORMAT_YVYU = 1431918169, SDL_PIXELFORMAT_NV12 = 842094158, SDL_PIXELFORMAT_NV21 = 825382478, SDL_PIXELFORMAT_EXTERNAL_OES = 542328143, _, }; pub const SDL_PixelFormatEnum = enum_unnamed_17; pub const struct_SDL_Color = extern struct { r: u8, g: u8, b: u8, a: u8, }; pub const SDL_Color = struct_SDL_Color; pub const struct_SDL_Palette = extern struct { ncolors: c_int, colors: [*c]SDL_Color, version: u32, refcount: c_int, }; pub const SDL_Palette = struct_SDL_Palette; pub const struct_SDL_PixelFormat = extern struct { format: u32, palette: [*c]SDL_Palette, BitsPerPixel: u8, BytesPerPixel: u8, padding: [2]u8, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32, Rloss: u8, Gloss: u8, Bloss: u8, Aloss: u8, Rshift: u8, Gshift: u8, Bshift: u8, Ashift: u8, refcount: c_int, next: [*c]struct_SDL_PixelFormat, }; pub const SDL_PixelFormat = struct_SDL_PixelFormat; pub extern fn SDL_GetPixelFormatName(format: u32) [*c]const u8; pub extern fn SDL_PixelFormatEnumToMasks(format: u32, bpp: [*c]c_int, Rmask: [*c]u32, Gmask: [*c]u32, Bmask: [*c]u32, Amask: [*c]u32) SDL_bool; pub extern fn SDL_MasksToPixelFormatEnum(bpp: c_int, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) u32; pub extern fn SDL_AllocFormat(pixel_format: u32) [*c]SDL_PixelFormat; pub extern fn SDL_FreeFormat(format: [*c]SDL_PixelFormat) void; pub extern fn SDL_AllocPalette(ncolors: c_int) [*c]SDL_Palette; pub extern fn SDL_SetPixelFormatPalette(format: [*c]SDL_PixelFormat, palette: [*c]SDL_Palette) c_int; pub extern fn SDL_SetPaletteColors(palette: [*c]SDL_Palette, colors: [*c]const SDL_Color, firstcolor: c_int, ncolors: c_int) c_int; pub extern fn SDL_FreePalette(palette: [*c]SDL_Palette) void; pub extern fn SDL_MapRGB(format: [*c]const SDL_PixelFormat, r: u8, g: u8, b: u8) u32; pub extern fn SDL_MapRGBA(format: [*c]const SDL_PixelFormat, r: u8, g: u8, b: u8, a: u8) u32; pub extern fn SDL_GetRGB(pixel: u32, format: [*c]const SDL_PixelFormat, r: [*c]u8, g: [*c]u8, b: [*c]u8) void; pub extern fn SDL_GetRGBA(pixel: u32, format: [*c]const SDL_PixelFormat, r: [*c]u8, g: [*c]u8, b: [*c]u8, a: [*c]u8) void; pub extern fn SDL_CalculateGammaRamp(gamma: f32, ramp: [*c]u16) void; pub const struct_SDL_Point = extern struct { x: c_int, y: c_int, }; pub const SDL_Point = struct_SDL_Point; pub const struct_SDL_FPoint = extern struct { x: f32, y: f32, }; pub const SDL_FPoint = struct_SDL_FPoint; pub const struct_SDL_Rect = extern struct { x: c_int, y: c_int, w: c_int, h: c_int, }; pub const SDL_Rect = struct_SDL_Rect; pub const struct_SDL_FRect = extern struct { x: f32, y: f32, w: f32, h: f32, }; pub const SDL_FRect = struct_SDL_FRect; pub fn SDL_PointInRect(arg_p: [*c]const SDL_Point, arg_r: [*c]const SDL_Rect) callconv(.C) SDL_bool { var p = arg_p; var r = arg_r; return @intToEnum(SDL_bool, if ((((p.*.x >= r.*.x) and (p.*.x < (r.*.x + r.*.w))) and (p.*.y >= r.*.y)) and (p.*.y < (r.*.y + r.*.h))) SDL_TRUE else SDL_FALSE); } pub fn SDL_RectEmpty(arg_r: [*c]const SDL_Rect) callconv(.C) SDL_bool { var r = arg_r; return @intToEnum(SDL_bool, if (((!(r != null)) or (r.*.w <= @as(c_int, 0))) or (r.*.h <= @as(c_int, 0))) SDL_TRUE else SDL_FALSE); } pub fn SDL_RectEquals(arg_a: [*c]const SDL_Rect, arg_b: [*c]const SDL_Rect) callconv(.C) SDL_bool { var a = arg_a; var b = arg_b; return @intToEnum(SDL_bool, if ((((((a != null) and (b != null)) and (a.*.x == b.*.x)) and (a.*.y == b.*.y)) and (a.*.w == b.*.w)) and (a.*.h == b.*.h)) SDL_TRUE else SDL_FALSE); } pub extern fn SDL_HasIntersection(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect) SDL_bool; pub extern fn SDL_IntersectRect(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect, result: [*c]SDL_Rect) SDL_bool; pub extern fn SDL_UnionRect(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect, result: [*c]SDL_Rect) void; pub extern fn SDL_EnclosePoints(points: [*c]const SDL_Point, count: c_int, clip: [*c]const SDL_Rect, result: [*c]SDL_Rect) SDL_bool; pub extern fn SDL_IntersectRectAndLine(rect: [*c]const SDL_Rect, X1: [*c]c_int, Y1: [*c]c_int, X2: [*c]c_int, Y2: [*c]c_int) SDL_bool; pub const SDL_BLENDMODE_NONE = @enumToInt(enum_unnamed_18.SDL_BLENDMODE_NONE); pub const SDL_BLENDMODE_BLEND = @enumToInt(enum_unnamed_18.SDL_BLENDMODE_BLEND); pub const SDL_BLENDMODE_ADD = @enumToInt(enum_unnamed_18.SDL_BLENDMODE_ADD); pub const SDL_BLENDMODE_MOD = @enumToInt(enum_unnamed_18.SDL_BLENDMODE_MOD); pub const SDL_BLENDMODE_MUL = @enumToInt(enum_unnamed_18.SDL_BLENDMODE_MUL); pub const SDL_BLENDMODE_INVALID = @enumToInt(enum_unnamed_18.SDL_BLENDMODE_INVALID); const enum_unnamed_18 = extern enum(c_int) { SDL_BLENDMODE_NONE = 0, SDL_BLENDMODE_BLEND = 1, SDL_BLENDMODE_ADD = 2, SDL_BLENDMODE_MOD = 4, SDL_BLENDMODE_MUL = 8, SDL_BLENDMODE_INVALID = 2147483647, _, }; pub const SDL_BlendMode = enum_unnamed_18; pub const SDL_BLENDOPERATION_ADD = @enumToInt(enum_unnamed_19.SDL_BLENDOPERATION_ADD); pub const SDL_BLENDOPERATION_SUBTRACT = @enumToInt(enum_unnamed_19.SDL_BLENDOPERATION_SUBTRACT); pub const SDL_BLENDOPERATION_REV_SUBTRACT = @enumToInt(enum_unnamed_19.SDL_BLENDOPERATION_REV_SUBTRACT); pub const SDL_BLENDOPERATION_MINIMUM = @enumToInt(enum_unnamed_19.SDL_BLENDOPERATION_MINIMUM); pub const SDL_BLENDOPERATION_MAXIMUM = @enumToInt(enum_unnamed_19.SDL_BLENDOPERATION_MAXIMUM); const enum_unnamed_19 = extern enum(c_int) { SDL_BLENDOPERATION_ADD = 1, SDL_BLENDOPERATION_SUBTRACT = 2, SDL_BLENDOPERATION_REV_SUBTRACT = 3, SDL_BLENDOPERATION_MINIMUM = 4, SDL_BLENDOPERATION_MAXIMUM = 5, _, }; pub const SDL_BlendOperation = enum_unnamed_19; pub const SDL_BLENDFACTOR_ZERO = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_ZERO); pub const SDL_BLENDFACTOR_ONE = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_ONE); pub const SDL_BLENDFACTOR_SRC_COLOR = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_SRC_COLOR); pub const SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR); pub const SDL_BLENDFACTOR_SRC_ALPHA = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_SRC_ALPHA); pub const SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA); pub const SDL_BLENDFACTOR_DST_COLOR = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_DST_COLOR); pub const SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR); pub const SDL_BLENDFACTOR_DST_ALPHA = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_DST_ALPHA); pub const SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = @enumToInt(enum_unnamed_20.SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA); const enum_unnamed_20 = extern enum(c_int) { SDL_BLENDFACTOR_ZERO = 1, SDL_BLENDFACTOR_ONE = 2, SDL_BLENDFACTOR_SRC_COLOR = 3, SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 4, SDL_BLENDFACTOR_SRC_ALPHA = 5, SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 6, SDL_BLENDFACTOR_DST_COLOR = 7, SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 8, SDL_BLENDFACTOR_DST_ALPHA = 9, SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 10, _, }; pub const SDL_BlendFactor = enum_unnamed_20; pub extern fn SDL_ComposeCustomBlendMode(srcColorFactor: SDL_BlendFactor, dstColorFactor: SDL_BlendFactor, colorOperation: SDL_BlendOperation, srcAlphaFactor: SDL_BlendFactor, dstAlphaFactor: SDL_BlendFactor, alphaOperation: SDL_BlendOperation) SDL_BlendMode; pub const struct_SDL_BlitMap = opaque {}; pub const struct_SDL_Surface = extern struct { flags: u32, format: [*c]SDL_PixelFormat, w: c_int, h: c_int, pitch: c_int, pixels: ?*c_void, userdata: ?*c_void, locked: c_int, list_blitmap: ?*c_void, clip_rect: SDL_Rect, map: ?*struct_SDL_BlitMap, refcount: c_int, }; pub const SDL_Surface = struct_SDL_Surface; pub const SDL_blit = ?fn ([*c]struct_SDL_Surface, [*c]SDL_Rect, [*c]struct_SDL_Surface, [*c]SDL_Rect) callconv(.C) c_int; pub const SDL_YUV_CONVERSION_JPEG = @enumToInt(enum_unnamed_21.SDL_YUV_CONVERSION_JPEG); pub const SDL_YUV_CONVERSION_BT601 = @enumToInt(enum_unnamed_21.SDL_YUV_CONVERSION_BT601); pub const SDL_YUV_CONVERSION_BT709 = @enumToInt(enum_unnamed_21.SDL_YUV_CONVERSION_BT709); pub const SDL_YUV_CONVERSION_AUTOMATIC = @enumToInt(enum_unnamed_21.SDL_YUV_CONVERSION_AUTOMATIC); const enum_unnamed_21 = extern enum(c_int) { SDL_YUV_CONVERSION_JPEG, SDL_YUV_CONVERSION_BT601, SDL_YUV_CONVERSION_BT709, SDL_YUV_CONVERSION_AUTOMATIC, _, }; pub const SDL_YUV_CONVERSION_MODE = enum_unnamed_21; pub extern fn SDL_CreateRGBSurface(flags: u32, width: c_int, height: c_int, depth: c_int, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceWithFormat(flags: u32, width: c_int, height: c_int, depth: c_int, format: u32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceFrom(pixels: ?*c_void, width: c_int, height: c_int, depth: c_int, pitch: c_int, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceWithFormatFrom(pixels: ?*c_void, width: c_int, height: c_int, depth: c_int, pitch: c_int, format: u32) [*c]SDL_Surface; pub extern fn SDL_FreeSurface(surface: [*c]SDL_Surface) void; pub extern fn SDL_SetSurfacePalette(surface: [*c]SDL_Surface, palette: [*c]SDL_Palette) c_int; pub extern fn SDL_LockSurface(surface: [*c]SDL_Surface) c_int; pub extern fn SDL_UnlockSurface(surface: [*c]SDL_Surface) void; pub extern fn SDL_LoadBMP_RW(src: [*c]SDL_RWops, freesrc: c_int) [*c]SDL_Surface; pub extern fn SDL_SaveBMP_RW(surface: [*c]SDL_Surface, dst: [*c]SDL_RWops, freedst: c_int) c_int; pub extern fn SDL_SetSurfaceRLE(surface: [*c]SDL_Surface, flag: c_int) c_int; pub extern fn SDL_HasSurfaceRLE(surface: [*c]SDL_Surface) SDL_bool; pub extern fn SDL_SetColorKey(surface: [*c]SDL_Surface, flag: c_int, key: u32) c_int; pub extern fn SDL_HasColorKey(surface: [*c]SDL_Surface) SDL_bool; pub extern fn SDL_GetColorKey(surface: [*c]SDL_Surface, key: [*c]u32) c_int; pub extern fn SDL_SetSurfaceColorMod(surface: [*c]SDL_Surface, r: u8, g: u8, b: u8) c_int; pub extern fn SDL_GetSurfaceColorMod(surface: [*c]SDL_Surface, r: [*c]u8, g: [*c]u8, b: [*c]u8) c_int; pub extern fn SDL_SetSurfaceAlphaMod(surface: [*c]SDL_Surface, alpha: u8) c_int; pub extern fn SDL_GetSurfaceAlphaMod(surface: [*c]SDL_Surface, alpha: [*c]u8) c_int; pub extern fn SDL_SetSurfaceBlendMode(surface: [*c]SDL_Surface, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetSurfaceBlendMode(surface: [*c]SDL_Surface, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_SetClipRect(surface: [*c]SDL_Surface, rect: [*c]const SDL_Rect) SDL_bool; pub extern fn SDL_GetClipRect(surface: [*c]SDL_Surface, rect: [*c]SDL_Rect) void; pub extern fn SDL_DuplicateSurface(surface: [*c]SDL_Surface) [*c]SDL_Surface; pub extern fn SDL_ConvertSurface(src: [*c]SDL_Surface, fmt: [*c]const SDL_PixelFormat, flags: u32) [*c]SDL_Surface; pub extern fn SDL_ConvertSurfaceFormat(src: [*c]SDL_Surface, pixel_format: u32, flags: u32) [*c]SDL_Surface; pub extern fn SDL_ConvertPixels(width: c_int, height: c_int, src_format: u32, src: ?*const c_void, src_pitch: c_int, dst_format: u32, dst: ?*c_void, dst_pitch: c_int) c_int; pub extern fn SDL_FillRect(dst: [*c]SDL_Surface, rect: [*c]const SDL_Rect, color: u32) c_int; pub extern fn SDL_FillRects(dst: [*c]SDL_Surface, rects: [*c]const SDL_Rect, count: c_int, color: u32) c_int; pub extern fn SDL_UpperBlit(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_LowerBlit(src: [*c]SDL_Surface, srcrect: [*c]SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_SoftStretch(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_SoftStretchLinear(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_UpperBlitScaled(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_LowerBlitScaled(src: [*c]SDL_Surface, srcrect: [*c]SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_SetYUVConversionMode(mode: SDL_YUV_CONVERSION_MODE) void; pub extern fn SDL_GetYUVConversionMode() SDL_YUV_CONVERSION_MODE; pub extern fn SDL_GetYUVConversionModeForResolution(width: c_int, height: c_int) SDL_YUV_CONVERSION_MODE; const struct_unnamed_22 = extern struct { format: u32, w: c_int, h: c_int, refresh_rate: c_int, driverdata: ?*c_void, }; pub const SDL_DisplayMode = struct_unnamed_22; pub const struct_SDL_Window = opaque {}; pub const SDL_Window = struct_SDL_Window; pub const SDL_WINDOW_FULLSCREEN = @enumToInt(enum_unnamed_23.SDL_WINDOW_FULLSCREEN); pub const SDL_WINDOW_OPENGL = @enumToInt(enum_unnamed_23.SDL_WINDOW_OPENGL); pub const SDL_WINDOW_SHOWN = @enumToInt(enum_unnamed_23.SDL_WINDOW_SHOWN); pub const SDL_WINDOW_HIDDEN = @enumToInt(enum_unnamed_23.SDL_WINDOW_HIDDEN); pub const SDL_WINDOW_BORDERLESS = @enumToInt(enum_unnamed_23.SDL_WINDOW_BORDERLESS); pub const SDL_WINDOW_RESIZABLE = @enumToInt(enum_unnamed_23.SDL_WINDOW_RESIZABLE); pub const SDL_WINDOW_MINIMIZED = @enumToInt(enum_unnamed_23.SDL_WINDOW_MINIMIZED); pub const SDL_WINDOW_MAXIMIZED = @enumToInt(enum_unnamed_23.SDL_WINDOW_MAXIMIZED); pub const SDL_WINDOW_INPUT_GRABBED = @enumToInt(enum_unnamed_23.SDL_WINDOW_INPUT_GRABBED); pub const SDL_WINDOW_INPUT_FOCUS = @enumToInt(enum_unnamed_23.SDL_WINDOW_INPUT_FOCUS); pub const SDL_WINDOW_MOUSE_FOCUS = @enumToInt(enum_unnamed_23.SDL_WINDOW_MOUSE_FOCUS); pub const SDL_WINDOW_FULLSCREEN_DESKTOP = @enumToInt(enum_unnamed_23.SDL_WINDOW_FULLSCREEN_DESKTOP); pub const SDL_WINDOW_FOREIGN = @enumToInt(enum_unnamed_23.SDL_WINDOW_FOREIGN); pub const SDL_WINDOW_ALLOW_HIGHDPI = @enumToInt(enum_unnamed_23.SDL_WINDOW_ALLOW_HIGHDPI); pub const SDL_WINDOW_MOUSE_CAPTURE = @enumToInt(enum_unnamed_23.SDL_WINDOW_MOUSE_CAPTURE); pub const SDL_WINDOW_ALWAYS_ON_TOP = @enumToInt(enum_unnamed_23.SDL_WINDOW_ALWAYS_ON_TOP); pub const SDL_WINDOW_SKIP_TASKBAR = @enumToInt(enum_unnamed_23.SDL_WINDOW_SKIP_TASKBAR); pub const SDL_WINDOW_UTILITY = @enumToInt(enum_unnamed_23.SDL_WINDOW_UTILITY); pub const SDL_WINDOW_TOOLTIP = @enumToInt(enum_unnamed_23.SDL_WINDOW_TOOLTIP); pub const SDL_WINDOW_POPUP_MENU = @enumToInt(enum_unnamed_23.SDL_WINDOW_POPUP_MENU); pub const SDL_WINDOW_VULKAN = @enumToInt(enum_unnamed_23.SDL_WINDOW_VULKAN); pub const SDL_WINDOW_METAL = @enumToInt(enum_unnamed_23.SDL_WINDOW_METAL); const enum_unnamed_23 = extern enum(c_int) { SDL_WINDOW_FULLSCREEN = 1, SDL_WINDOW_OPENGL = 2, SDL_WINDOW_SHOWN = 4, SDL_WINDOW_HIDDEN = 8, SDL_WINDOW_BORDERLESS = 16, SDL_WINDOW_RESIZABLE = 32, SDL_WINDOW_MINIMIZED = 64, SDL_WINDOW_MAXIMIZED = 128, SDL_WINDOW_INPUT_GRABBED = 256, SDL_WINDOW_INPUT_FOCUS = 512, SDL_WINDOW_MOUSE_FOCUS = 1024, SDL_WINDOW_FULLSCREEN_DESKTOP = 4097, SDL_WINDOW_FOREIGN = 2048, SDL_WINDOW_ALLOW_HIGHDPI = 8192, SDL_WINDOW_MOUSE_CAPTURE = 16384, SDL_WINDOW_ALWAYS_ON_TOP = 32768, SDL_WINDOW_SKIP_TASKBAR = 65536, SDL_WINDOW_UTILITY = 131072, SDL_WINDOW_TOOLTIP = 262144, SDL_WINDOW_POPUP_MENU = 524288, SDL_WINDOW_VULKAN = 268435456, SDL_WINDOW_METAL = 536870912, _, }; pub const SDL_WindowFlags = enum_unnamed_23; pub const SDL_WINDOWEVENT_NONE = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_NONE); pub const SDL_WINDOWEVENT_SHOWN = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_SHOWN); pub const SDL_WINDOWEVENT_HIDDEN = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_HIDDEN); pub const SDL_WINDOWEVENT_EXPOSED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_EXPOSED); pub const SDL_WINDOWEVENT_MOVED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_MOVED); pub const SDL_WINDOWEVENT_RESIZED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_RESIZED); pub const SDL_WINDOWEVENT_SIZE_CHANGED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_SIZE_CHANGED); pub const SDL_WINDOWEVENT_MINIMIZED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_MINIMIZED); pub const SDL_WINDOWEVENT_MAXIMIZED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_MAXIMIZED); pub const SDL_WINDOWEVENT_RESTORED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_RESTORED); pub const SDL_WINDOWEVENT_ENTER = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_ENTER); pub const SDL_WINDOWEVENT_LEAVE = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_LEAVE); pub const SDL_WINDOWEVENT_FOCUS_GAINED = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_FOCUS_GAINED); pub const SDL_WINDOWEVENT_FOCUS_LOST = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_FOCUS_LOST); pub const SDL_WINDOWEVENT_CLOSE = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_CLOSE); pub const SDL_WINDOWEVENT_TAKE_FOCUS = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_TAKE_FOCUS); pub const SDL_WINDOWEVENT_HIT_TEST = @enumToInt(enum_unnamed_24.SDL_WINDOWEVENT_HIT_TEST); const enum_unnamed_24 = extern enum(c_int) { SDL_WINDOWEVENT_NONE, SDL_WINDOWEVENT_SHOWN, SDL_WINDOWEVENT_HIDDEN, SDL_WINDOWEVENT_EXPOSED, SDL_WINDOWEVENT_MOVED, SDL_WINDOWEVENT_RESIZED, SDL_WINDOWEVENT_SIZE_CHANGED, SDL_WINDOWEVENT_MINIMIZED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED, SDL_WINDOWEVENT_ENTER, SDL_WINDOWEVENT_LEAVE, SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_CLOSE, SDL_WINDOWEVENT_TAKE_FOCUS, SDL_WINDOWEVENT_HIT_TEST, _, }; pub const SDL_WindowEventID = enum_unnamed_24; pub const SDL_DISPLAYEVENT_NONE = @enumToInt(enum_unnamed_25.SDL_DISPLAYEVENT_NONE); pub const SDL_DISPLAYEVENT_ORIENTATION = @enumToInt(enum_unnamed_25.SDL_DISPLAYEVENT_ORIENTATION); pub const SDL_DISPLAYEVENT_CONNECTED = @enumToInt(enum_unnamed_25.SDL_DISPLAYEVENT_CONNECTED); pub const SDL_DISPLAYEVENT_DISCONNECTED = @enumToInt(enum_unnamed_25.SDL_DISPLAYEVENT_DISCONNECTED); const enum_unnamed_25 = extern enum(c_int) { SDL_DISPLAYEVENT_NONE, SDL_DISPLAYEVENT_ORIENTATION, SDL_DISPLAYEVENT_CONNECTED, SDL_DISPLAYEVENT_DISCONNECTED, _, }; pub const SDL_DisplayEventID = enum_unnamed_25; pub const SDL_ORIENTATION_UNKNOWN = @enumToInt(enum_unnamed_26.SDL_ORIENTATION_UNKNOWN); pub const SDL_ORIENTATION_LANDSCAPE = @enumToInt(enum_unnamed_26.SDL_ORIENTATION_LANDSCAPE); pub const SDL_ORIENTATION_LANDSCAPE_FLIPPED = @enumToInt(enum_unnamed_26.SDL_ORIENTATION_LANDSCAPE_FLIPPED); pub const SDL_ORIENTATION_PORTRAIT = @enumToInt(enum_unnamed_26.SDL_ORIENTATION_PORTRAIT); pub const SDL_ORIENTATION_PORTRAIT_FLIPPED = @enumToInt(enum_unnamed_26.SDL_ORIENTATION_PORTRAIT_FLIPPED); const enum_unnamed_26 = extern enum(c_int) { SDL_ORIENTATION_UNKNOWN, SDL_ORIENTATION_LANDSCAPE, SDL_ORIENTATION_LANDSCAPE_FLIPPED, SDL_ORIENTATION_PORTRAIT, SDL_ORIENTATION_PORTRAIT_FLIPPED, _, }; pub const SDL_DisplayOrientation = enum_unnamed_26; pub const SDL_GLContext = ?*c_void; pub const SDL_GL_RED_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_RED_SIZE); pub const SDL_GL_GREEN_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_GREEN_SIZE); pub const SDL_GL_BLUE_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_BLUE_SIZE); pub const SDL_GL_ALPHA_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_ALPHA_SIZE); pub const SDL_GL_BUFFER_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_BUFFER_SIZE); pub const SDL_GL_DOUBLEBUFFER = @enumToInt(enum_unnamed_27.SDL_GL_DOUBLEBUFFER); pub const SDL_GL_DEPTH_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_DEPTH_SIZE); pub const SDL_GL_STENCIL_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_STENCIL_SIZE); pub const SDL_GL_ACCUM_RED_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_ACCUM_RED_SIZE); pub const SDL_GL_ACCUM_GREEN_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_ACCUM_GREEN_SIZE); pub const SDL_GL_ACCUM_BLUE_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_ACCUM_BLUE_SIZE); pub const SDL_GL_ACCUM_ALPHA_SIZE = @enumToInt(enum_unnamed_27.SDL_GL_ACCUM_ALPHA_SIZE); pub const SDL_GL_STEREO = @enumToInt(enum_unnamed_27.SDL_GL_STEREO); pub const SDL_GL_MULTISAMPLEBUFFERS = @enumToInt(enum_unnamed_27.SDL_GL_MULTISAMPLEBUFFERS); pub const SDL_GL_MULTISAMPLESAMPLES = @enumToInt(enum_unnamed_27.SDL_GL_MULTISAMPLESAMPLES); pub const SDL_GL_ACCELERATED_VISUAL = @enumToInt(enum_unnamed_27.SDL_GL_ACCELERATED_VISUAL); pub const SDL_GL_RETAINED_BACKING = @enumToInt(enum_unnamed_27.SDL_GL_RETAINED_BACKING); pub const SDL_GL_CONTEXT_MAJOR_VERSION = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_MAJOR_VERSION); pub const SDL_GL_CONTEXT_MINOR_VERSION = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_MINOR_VERSION); pub const SDL_GL_CONTEXT_EGL = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_EGL); pub const SDL_GL_CONTEXT_FLAGS = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_FLAGS); pub const SDL_GL_CONTEXT_PROFILE_MASK = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_PROFILE_MASK); pub const SDL_GL_SHARE_WITH_CURRENT_CONTEXT = @enumToInt(enum_unnamed_27.SDL_GL_SHARE_WITH_CURRENT_CONTEXT); pub const SDL_GL_FRAMEBUFFER_SRGB_CAPABLE = @enumToInt(enum_unnamed_27.SDL_GL_FRAMEBUFFER_SRGB_CAPABLE); pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_RELEASE_BEHAVIOR); pub const SDL_GL_CONTEXT_RESET_NOTIFICATION = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_RESET_NOTIFICATION); pub const SDL_GL_CONTEXT_NO_ERROR = @enumToInt(enum_unnamed_27.SDL_GL_CONTEXT_NO_ERROR); const enum_unnamed_27 = extern enum(c_int) { SDL_GL_RED_SIZE, SDL_GL_GREEN_SIZE, SDL_GL_BLUE_SIZE, SDL_GL_ALPHA_SIZE, SDL_GL_BUFFER_SIZE, SDL_GL_DOUBLEBUFFER, SDL_GL_DEPTH_SIZE, SDL_GL_STENCIL_SIZE, SDL_GL_ACCUM_RED_SIZE, SDL_GL_ACCUM_GREEN_SIZE, SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_ALPHA_SIZE, SDL_GL_STEREO, SDL_GL_MULTISAMPLEBUFFERS, SDL_GL_MULTISAMPLESAMPLES, SDL_GL_ACCELERATED_VISUAL, SDL_GL_RETAINED_BACKING, SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION, SDL_GL_CONTEXT_EGL, SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_SHARE_WITH_CURRENT_CONTEXT, SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, SDL_GL_CONTEXT_RELEASE_BEHAVIOR, SDL_GL_CONTEXT_RESET_NOTIFICATION, SDL_GL_CONTEXT_NO_ERROR, _, }; pub const SDL_GLattr = enum_unnamed_27; pub const SDL_GL_CONTEXT_PROFILE_CORE = @enumToInt(enum_unnamed_28.SDL_GL_CONTEXT_PROFILE_CORE); pub const SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = @enumToInt(enum_unnamed_28.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); pub const SDL_GL_CONTEXT_PROFILE_ES = @enumToInt(enum_unnamed_28.SDL_GL_CONTEXT_PROFILE_ES); const enum_unnamed_28 = extern enum(c_int) { SDL_GL_CONTEXT_PROFILE_CORE = 1, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 2, SDL_GL_CONTEXT_PROFILE_ES = 4, _, }; pub const SDL_GLprofile = enum_unnamed_28; pub const SDL_GL_CONTEXT_DEBUG_FLAG = @enumToInt(enum_unnamed_29.SDL_GL_CONTEXT_DEBUG_FLAG); pub const SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = @enumToInt(enum_unnamed_29.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); pub const SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = @enumToInt(enum_unnamed_29.SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG); pub const SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = @enumToInt(enum_unnamed_29.SDL_GL_CONTEXT_RESET_ISOLATION_FLAG); const enum_unnamed_29 = extern enum(c_int) { SDL_GL_CONTEXT_DEBUG_FLAG = 1, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 2, SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 4, SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 8, _, }; pub const SDL_GLcontextFlag = enum_unnamed_29; pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = @enumToInt(enum_unnamed_30.SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE); pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = @enumToInt(enum_unnamed_30.SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH); const enum_unnamed_30 = extern enum(c_int) { SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0, SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 1, _, }; pub const SDL_GLcontextReleaseFlag = enum_unnamed_30; pub const SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = @enumToInt(enum_unnamed_31.SDL_GL_CONTEXT_RESET_NO_NOTIFICATION); pub const SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = @enumToInt(enum_unnamed_31.SDL_GL_CONTEXT_RESET_LOSE_CONTEXT); const enum_unnamed_31 = extern enum(c_int) { SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0, SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 1, _, }; pub const SDL_GLContextResetNotification = enum_unnamed_31; pub extern fn SDL_GetNumVideoDrivers() c_int; pub extern fn SDL_GetVideoDriver(index: c_int) [*c]const u8; pub extern fn SDL_VideoInit(driver_name: [*c]const u8) c_int; pub extern fn SDL_VideoQuit() void; pub extern fn SDL_GetCurrentVideoDriver() [*c]const u8; pub extern fn SDL_GetNumVideoDisplays() c_int; pub extern fn SDL_GetDisplayName(displayIndex: c_int) [*c]const u8; pub extern fn SDL_GetDisplayBounds(displayIndex: c_int, rect: [*c]SDL_Rect) c_int; pub extern fn SDL_GetDisplayUsableBounds(displayIndex: c_int, rect: [*c]SDL_Rect) c_int; pub extern fn SDL_GetDisplayDPI(displayIndex: c_int, ddpi: [*c]f32, hdpi: [*c]f32, vdpi: [*c]f32) c_int; pub extern fn SDL_GetDisplayOrientation(displayIndex: c_int) SDL_DisplayOrientation; pub extern fn SDL_GetNumDisplayModes(displayIndex: c_int) c_int; pub extern fn SDL_GetDisplayMode(displayIndex: c_int, modeIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetDesktopDisplayMode(displayIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetCurrentDisplayMode(displayIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetClosestDisplayMode(displayIndex: c_int, mode: [*c]const SDL_DisplayMode, closest: [*c]SDL_DisplayMode) [*c]SDL_DisplayMode; pub extern fn SDL_GetWindowDisplayIndex(window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowDisplayMode(window: ?*SDL_Window, mode: [*c]const SDL_DisplayMode) c_int; pub extern fn SDL_GetWindowDisplayMode(window: ?*SDL_Window, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetWindowPixelFormat(window: ?*SDL_Window) u32; pub extern fn SDL_CreateWindow(title: [*c]const u8, x: c_int, y: c_int, w: c_int, h: c_int, flags: u32) ?*SDL_Window; pub extern fn SDL_CreateWindowFrom(data: ?*const c_void) ?*SDL_Window; pub extern fn SDL_GetWindowID(window: ?*SDL_Window) u32; pub extern fn SDL_GetWindowFromID(id: u32) ?*SDL_Window; pub extern fn SDL_GetWindowFlags(window: ?*SDL_Window) u32; pub extern fn SDL_SetWindowTitle(window: ?*SDL_Window, title: [*c]const u8) void; pub extern fn SDL_GetWindowTitle(window: ?*SDL_Window) [*c]const u8; pub extern fn SDL_SetWindowIcon(window: ?*SDL_Window, icon: [*c]SDL_Surface) void; pub extern fn SDL_SetWindowData(window: ?*SDL_Window, name: [*c]const u8, userdata: ?*c_void) ?*c_void; pub extern fn SDL_GetWindowData(window: ?*SDL_Window, name: [*c]const u8) ?*c_void; pub extern fn SDL_SetWindowPosition(window: ?*SDL_Window, x: c_int, y: c_int) void; pub extern fn SDL_GetWindowPosition(window: ?*SDL_Window, x: [*c]c_int, y: [*c]c_int) void; pub extern fn SDL_SetWindowSize(window: ?*SDL_Window, w: c_int, h: c_int) void; pub extern fn SDL_GetWindowSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_GetWindowBordersSize(window: ?*SDL_Window, top: [*c]c_int, left: [*c]c_int, bottom: [*c]c_int, right: [*c]c_int) c_int; pub extern fn SDL_SetWindowMinimumSize(window: ?*SDL_Window, min_w: c_int, min_h: c_int) void; pub extern fn SDL_GetWindowMinimumSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_SetWindowMaximumSize(window: ?*SDL_Window, max_w: c_int, max_h: c_int) void; pub extern fn SDL_GetWindowMaximumSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_SetWindowBordered(window: ?*SDL_Window, bordered: SDL_bool) void; pub extern fn SDL_SetWindowResizable(window: ?*SDL_Window, resizable: SDL_bool) void; pub extern fn SDL_ShowWindow(window: ?*SDL_Window) void; pub extern fn SDL_HideWindow(window: ?*SDL_Window) void; pub extern fn SDL_RaiseWindow(window: ?*SDL_Window) void; pub extern fn SDL_MaximizeWindow(window: ?*SDL_Window) void; pub extern fn SDL_MinimizeWindow(window: ?*SDL_Window) void; pub extern fn SDL_RestoreWindow(window: ?*SDL_Window) void; pub extern fn SDL_SetWindowFullscreen(window: ?*SDL_Window, flags: u32) c_int; pub extern fn SDL_GetWindowSurface(window: ?*SDL_Window) [*c]SDL_Surface; pub extern fn SDL_UpdateWindowSurface(window: ?*SDL_Window) c_int; pub extern fn SDL_UpdateWindowSurfaceRects(window: ?*SDL_Window, rects: [*c]const SDL_Rect, numrects: c_int) c_int; pub extern fn SDL_SetWindowGrab(window: ?*SDL_Window, grabbed: SDL_bool) void; pub extern fn SDL_GetWindowGrab(window: ?*SDL_Window) SDL_bool; pub extern fn SDL_GetGrabbedWindow() ?*SDL_Window; pub extern fn SDL_SetWindowBrightness(window: ?*SDL_Window, brightness: f32) c_int; pub extern fn SDL_GetWindowBrightness(window: ?*SDL_Window) f32; pub extern fn SDL_SetWindowOpacity(window: ?*SDL_Window, opacity: f32) c_int; pub extern fn SDL_GetWindowOpacity(window: ?*SDL_Window, out_opacity: [*c]f32) c_int; pub extern fn SDL_SetWindowModalFor(modal_window: ?*SDL_Window, parent_window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowInputFocus(window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowGammaRamp(window: ?*SDL_Window, red: [*c]const u16, green: [*c]const u16, blue: [*c]const u16) c_int; pub extern fn SDL_GetWindowGammaRamp(window: ?*SDL_Window, red: [*c]u16, green: [*c]u16, blue: [*c]u16) c_int; pub const SDL_HITTEST_NORMAL = @enumToInt(enum_unnamed_32.SDL_HITTEST_NORMAL); pub const SDL_HITTEST_DRAGGABLE = @enumToInt(enum_unnamed_32.SDL_HITTEST_DRAGGABLE); pub const SDL_HITTEST_RESIZE_TOPLEFT = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_TOPLEFT); pub const SDL_HITTEST_RESIZE_TOP = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_TOP); pub const SDL_HITTEST_RESIZE_TOPRIGHT = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_TOPRIGHT); pub const SDL_HITTEST_RESIZE_RIGHT = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_RIGHT); pub const SDL_HITTEST_RESIZE_BOTTOMRIGHT = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_BOTTOMRIGHT); pub const SDL_HITTEST_RESIZE_BOTTOM = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_BOTTOM); pub const SDL_HITTEST_RESIZE_BOTTOMLEFT = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_BOTTOMLEFT); pub const SDL_HITTEST_RESIZE_LEFT = @enumToInt(enum_unnamed_32.SDL_HITTEST_RESIZE_LEFT); const enum_unnamed_32 = extern enum(c_int) { SDL_HITTEST_NORMAL, SDL_HITTEST_DRAGGABLE, SDL_HITTEST_RESIZE_TOPLEFT, SDL_HITTEST_RESIZE_TOP, SDL_HITTEST_RESIZE_TOPRIGHT, SDL_HITTEST_RESIZE_RIGHT, SDL_HITTEST_RESIZE_BOTTOMRIGHT, SDL_HITTEST_RESIZE_BOTTOM, SDL_HITTEST_RESIZE_BOTTOMLEFT, SDL_HITTEST_RESIZE_LEFT, _, }; pub const SDL_HitTestResult = enum_unnamed_32; pub const SDL_HitTest = ?fn (?*SDL_Window, [*c]const SDL_Point, ?*c_void) callconv(.C) SDL_HitTestResult; pub extern fn SDL_SetWindowHitTest(window: ?*SDL_Window, callback: SDL_HitTest, callback_data: ?*c_void) c_int; pub extern fn SDL_DestroyWindow(window: ?*SDL_Window) void; pub extern fn SDL_IsScreenSaverEnabled() SDL_bool; pub extern fn SDL_EnableScreenSaver() void; pub extern fn SDL_DisableScreenSaver() void; pub extern fn SDL_GL_LoadLibrary(path: [*c]const u8) c_int; pub extern fn SDL_GL_GetProcAddress(proc: [*c]const u8) ?*c_void; pub extern fn SDL_GL_UnloadLibrary() void; pub extern fn SDL_GL_ExtensionSupported(extension: [*c]const u8) SDL_bool; pub extern fn SDL_GL_ResetAttributes() void; pub extern fn SDL_GL_SetAttribute(attr: SDL_GLattr, value: c_int) c_int; pub extern fn SDL_GL_GetAttribute(attr: SDL_GLattr, value: [*c]c_int) c_int; pub extern fn SDL_GL_CreateContext(window: ?*SDL_Window) SDL_GLContext; pub extern fn SDL_GL_MakeCurrent(window: ?*SDL_Window, context: SDL_GLContext) c_int; pub extern fn SDL_GL_GetCurrentWindow() ?*SDL_Window; pub extern fn SDL_GL_GetCurrentContext() SDL_GLContext; pub extern fn SDL_GL_GetDrawableSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_GL_SetSwapInterval(interval: c_int) c_int; pub extern fn SDL_GL_GetSwapInterval() c_int; pub extern fn SDL_GL_SwapWindow(window: ?*SDL_Window) void; pub extern fn SDL_GL_DeleteContext(context: SDL_GLContext) void; pub const SDL_SCANCODE_UNKNOWN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_UNKNOWN); pub const SDL_SCANCODE_A = @enumToInt(enum_unnamed_33.SDL_SCANCODE_A); pub const SDL_SCANCODE_B = @enumToInt(enum_unnamed_33.SDL_SCANCODE_B); pub const SDL_SCANCODE_C = @enumToInt(enum_unnamed_33.SDL_SCANCODE_C); pub const SDL_SCANCODE_D = @enumToInt(enum_unnamed_33.SDL_SCANCODE_D); pub const SDL_SCANCODE_E = @enumToInt(enum_unnamed_33.SDL_SCANCODE_E); pub const SDL_SCANCODE_F = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F); pub const SDL_SCANCODE_G = @enumToInt(enum_unnamed_33.SDL_SCANCODE_G); pub const SDL_SCANCODE_H = @enumToInt(enum_unnamed_33.SDL_SCANCODE_H); pub const SDL_SCANCODE_I = @enumToInt(enum_unnamed_33.SDL_SCANCODE_I); pub const SDL_SCANCODE_J = @enumToInt(enum_unnamed_33.SDL_SCANCODE_J); pub const SDL_SCANCODE_K = @enumToInt(enum_unnamed_33.SDL_SCANCODE_K); pub const SDL_SCANCODE_L = @enumToInt(enum_unnamed_33.SDL_SCANCODE_L); pub const SDL_SCANCODE_M = @enumToInt(enum_unnamed_33.SDL_SCANCODE_M); pub const SDL_SCANCODE_N = @enumToInt(enum_unnamed_33.SDL_SCANCODE_N); pub const SDL_SCANCODE_O = @enumToInt(enum_unnamed_33.SDL_SCANCODE_O); pub const SDL_SCANCODE_P = @enumToInt(enum_unnamed_33.SDL_SCANCODE_P); pub const SDL_SCANCODE_Q = @enumToInt(enum_unnamed_33.SDL_SCANCODE_Q); pub const SDL_SCANCODE_R = @enumToInt(enum_unnamed_33.SDL_SCANCODE_R); pub const SDL_SCANCODE_S = @enumToInt(enum_unnamed_33.SDL_SCANCODE_S); pub const SDL_SCANCODE_T = @enumToInt(enum_unnamed_33.SDL_SCANCODE_T); pub const SDL_SCANCODE_U = @enumToInt(enum_unnamed_33.SDL_SCANCODE_U); pub const SDL_SCANCODE_V = @enumToInt(enum_unnamed_33.SDL_SCANCODE_V); pub const SDL_SCANCODE_W = @enumToInt(enum_unnamed_33.SDL_SCANCODE_W); pub const SDL_SCANCODE_X = @enumToInt(enum_unnamed_33.SDL_SCANCODE_X); pub const SDL_SCANCODE_Y = @enumToInt(enum_unnamed_33.SDL_SCANCODE_Y); pub const SDL_SCANCODE_Z = @enumToInt(enum_unnamed_33.SDL_SCANCODE_Z); pub const SDL_SCANCODE_1 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_1); pub const SDL_SCANCODE_2 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_2); pub const SDL_SCANCODE_3 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_3); pub const SDL_SCANCODE_4 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_4); pub const SDL_SCANCODE_5 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_5); pub const SDL_SCANCODE_6 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_6); pub const SDL_SCANCODE_7 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_7); pub const SDL_SCANCODE_8 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_8); pub const SDL_SCANCODE_9 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_9); pub const SDL_SCANCODE_0 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_0); pub const SDL_SCANCODE_RETURN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RETURN); pub const SDL_SCANCODE_ESCAPE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_ESCAPE); pub const SDL_SCANCODE_BACKSPACE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_BACKSPACE); pub const SDL_SCANCODE_TAB = @enumToInt(enum_unnamed_33.SDL_SCANCODE_TAB); pub const SDL_SCANCODE_SPACE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SPACE); pub const SDL_SCANCODE_MINUS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_MINUS); pub const SDL_SCANCODE_EQUALS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_EQUALS); pub const SDL_SCANCODE_LEFTBRACKET = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LEFTBRACKET); pub const SDL_SCANCODE_RIGHTBRACKET = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RIGHTBRACKET); pub const SDL_SCANCODE_BACKSLASH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_BACKSLASH); pub const SDL_SCANCODE_NONUSHASH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_NONUSHASH); pub const SDL_SCANCODE_SEMICOLON = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SEMICOLON); pub const SDL_SCANCODE_APOSTROPHE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_APOSTROPHE); pub const SDL_SCANCODE_GRAVE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_GRAVE); pub const SDL_SCANCODE_COMMA = @enumToInt(enum_unnamed_33.SDL_SCANCODE_COMMA); pub const SDL_SCANCODE_PERIOD = @enumToInt(enum_unnamed_33.SDL_SCANCODE_PERIOD); pub const SDL_SCANCODE_SLASH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SLASH); pub const SDL_SCANCODE_CAPSLOCK = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CAPSLOCK); pub const SDL_SCANCODE_F1 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F1); pub const SDL_SCANCODE_F2 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F2); pub const SDL_SCANCODE_F3 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F3); pub const SDL_SCANCODE_F4 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F4); pub const SDL_SCANCODE_F5 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F5); pub const SDL_SCANCODE_F6 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F6); pub const SDL_SCANCODE_F7 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F7); pub const SDL_SCANCODE_F8 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F8); pub const SDL_SCANCODE_F9 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F9); pub const SDL_SCANCODE_F10 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F10); pub const SDL_SCANCODE_F11 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F11); pub const SDL_SCANCODE_F12 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F12); pub const SDL_SCANCODE_PRINTSCREEN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_PRINTSCREEN); pub const SDL_SCANCODE_SCROLLLOCK = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SCROLLLOCK); pub const SDL_SCANCODE_PAUSE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_PAUSE); pub const SDL_SCANCODE_INSERT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INSERT); pub const SDL_SCANCODE_HOME = @enumToInt(enum_unnamed_33.SDL_SCANCODE_HOME); pub const SDL_SCANCODE_PAGEUP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_PAGEUP); pub const SDL_SCANCODE_DELETE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_DELETE); pub const SDL_SCANCODE_END = @enumToInt(enum_unnamed_33.SDL_SCANCODE_END); pub const SDL_SCANCODE_PAGEDOWN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_PAGEDOWN); pub const SDL_SCANCODE_RIGHT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RIGHT); pub const SDL_SCANCODE_LEFT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LEFT); pub const SDL_SCANCODE_DOWN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_DOWN); pub const SDL_SCANCODE_UP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_UP); pub const SDL_SCANCODE_NUMLOCKCLEAR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_NUMLOCKCLEAR); pub const SDL_SCANCODE_KP_DIVIDE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_DIVIDE); pub const SDL_SCANCODE_KP_MULTIPLY = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MULTIPLY); pub const SDL_SCANCODE_KP_MINUS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MINUS); pub const SDL_SCANCODE_KP_PLUS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_PLUS); pub const SDL_SCANCODE_KP_ENTER = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_ENTER); pub const SDL_SCANCODE_KP_1 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_1); pub const SDL_SCANCODE_KP_2 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_2); pub const SDL_SCANCODE_KP_3 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_3); pub const SDL_SCANCODE_KP_4 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_4); pub const SDL_SCANCODE_KP_5 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_5); pub const SDL_SCANCODE_KP_6 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_6); pub const SDL_SCANCODE_KP_7 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_7); pub const SDL_SCANCODE_KP_8 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_8); pub const SDL_SCANCODE_KP_9 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_9); pub const SDL_SCANCODE_KP_0 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_0); pub const SDL_SCANCODE_KP_PERIOD = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_PERIOD); pub const SDL_SCANCODE_NONUSBACKSLASH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_NONUSBACKSLASH); pub const SDL_SCANCODE_APPLICATION = @enumToInt(enum_unnamed_33.SDL_SCANCODE_APPLICATION); pub const SDL_SCANCODE_POWER = @enumToInt(enum_unnamed_33.SDL_SCANCODE_POWER); pub const SDL_SCANCODE_KP_EQUALS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_EQUALS); pub const SDL_SCANCODE_F13 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F13); pub const SDL_SCANCODE_F14 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F14); pub const SDL_SCANCODE_F15 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F15); pub const SDL_SCANCODE_F16 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F16); pub const SDL_SCANCODE_F17 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F17); pub const SDL_SCANCODE_F18 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F18); pub const SDL_SCANCODE_F19 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F19); pub const SDL_SCANCODE_F20 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F20); pub const SDL_SCANCODE_F21 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F21); pub const SDL_SCANCODE_F22 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F22); pub const SDL_SCANCODE_F23 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F23); pub const SDL_SCANCODE_F24 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_F24); pub const SDL_SCANCODE_EXECUTE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_EXECUTE); pub const SDL_SCANCODE_HELP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_HELP); pub const SDL_SCANCODE_MENU = @enumToInt(enum_unnamed_33.SDL_SCANCODE_MENU); pub const SDL_SCANCODE_SELECT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SELECT); pub const SDL_SCANCODE_STOP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_STOP); pub const SDL_SCANCODE_AGAIN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AGAIN); pub const SDL_SCANCODE_UNDO = @enumToInt(enum_unnamed_33.SDL_SCANCODE_UNDO); pub const SDL_SCANCODE_CUT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CUT); pub const SDL_SCANCODE_COPY = @enumToInt(enum_unnamed_33.SDL_SCANCODE_COPY); pub const SDL_SCANCODE_PASTE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_PASTE); pub const SDL_SCANCODE_FIND = @enumToInt(enum_unnamed_33.SDL_SCANCODE_FIND); pub const SDL_SCANCODE_MUTE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_MUTE); pub const SDL_SCANCODE_VOLUMEUP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_VOLUMEUP); pub const SDL_SCANCODE_VOLUMEDOWN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_VOLUMEDOWN); pub const SDL_SCANCODE_KP_COMMA = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_COMMA); pub const SDL_SCANCODE_KP_EQUALSAS400 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_EQUALSAS400); pub const SDL_SCANCODE_INTERNATIONAL1 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL1); pub const SDL_SCANCODE_INTERNATIONAL2 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL2); pub const SDL_SCANCODE_INTERNATIONAL3 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL3); pub const SDL_SCANCODE_INTERNATIONAL4 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL4); pub const SDL_SCANCODE_INTERNATIONAL5 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL5); pub const SDL_SCANCODE_INTERNATIONAL6 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL6); pub const SDL_SCANCODE_INTERNATIONAL7 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL7); pub const SDL_SCANCODE_INTERNATIONAL8 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL8); pub const SDL_SCANCODE_INTERNATIONAL9 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_INTERNATIONAL9); pub const SDL_SCANCODE_LANG1 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG1); pub const SDL_SCANCODE_LANG2 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG2); pub const SDL_SCANCODE_LANG3 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG3); pub const SDL_SCANCODE_LANG4 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG4); pub const SDL_SCANCODE_LANG5 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG5); pub const SDL_SCANCODE_LANG6 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG6); pub const SDL_SCANCODE_LANG7 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG7); pub const SDL_SCANCODE_LANG8 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG8); pub const SDL_SCANCODE_LANG9 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LANG9); pub const SDL_SCANCODE_ALTERASE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_ALTERASE); pub const SDL_SCANCODE_SYSREQ = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SYSREQ); pub const SDL_SCANCODE_CANCEL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CANCEL); pub const SDL_SCANCODE_CLEAR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CLEAR); pub const SDL_SCANCODE_PRIOR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_PRIOR); pub const SDL_SCANCODE_RETURN2 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RETURN2); pub const SDL_SCANCODE_SEPARATOR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SEPARATOR); pub const SDL_SCANCODE_OUT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_OUT); pub const SDL_SCANCODE_OPER = @enumToInt(enum_unnamed_33.SDL_SCANCODE_OPER); pub const SDL_SCANCODE_CLEARAGAIN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CLEARAGAIN); pub const SDL_SCANCODE_CRSEL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CRSEL); pub const SDL_SCANCODE_EXSEL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_EXSEL); pub const SDL_SCANCODE_KP_00 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_00); pub const SDL_SCANCODE_KP_000 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_000); pub const SDL_SCANCODE_THOUSANDSSEPARATOR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_THOUSANDSSEPARATOR); pub const SDL_SCANCODE_DECIMALSEPARATOR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_DECIMALSEPARATOR); pub const SDL_SCANCODE_CURRENCYUNIT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CURRENCYUNIT); pub const SDL_SCANCODE_CURRENCYSUBUNIT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CURRENCYSUBUNIT); pub const SDL_SCANCODE_KP_LEFTPAREN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_LEFTPAREN); pub const SDL_SCANCODE_KP_RIGHTPAREN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_RIGHTPAREN); pub const SDL_SCANCODE_KP_LEFTBRACE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_LEFTBRACE); pub const SDL_SCANCODE_KP_RIGHTBRACE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_RIGHTBRACE); pub const SDL_SCANCODE_KP_TAB = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_TAB); pub const SDL_SCANCODE_KP_BACKSPACE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_BACKSPACE); pub const SDL_SCANCODE_KP_A = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_A); pub const SDL_SCANCODE_KP_B = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_B); pub const SDL_SCANCODE_KP_C = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_C); pub const SDL_SCANCODE_KP_D = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_D); pub const SDL_SCANCODE_KP_E = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_E); pub const SDL_SCANCODE_KP_F = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_F); pub const SDL_SCANCODE_KP_XOR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_XOR); pub const SDL_SCANCODE_KP_POWER = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_POWER); pub const SDL_SCANCODE_KP_PERCENT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_PERCENT); pub const SDL_SCANCODE_KP_LESS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_LESS); pub const SDL_SCANCODE_KP_GREATER = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_GREATER); pub const SDL_SCANCODE_KP_AMPERSAND = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_AMPERSAND); pub const SDL_SCANCODE_KP_DBLAMPERSAND = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_DBLAMPERSAND); pub const SDL_SCANCODE_KP_VERTICALBAR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_VERTICALBAR); pub const SDL_SCANCODE_KP_DBLVERTICALBAR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_DBLVERTICALBAR); pub const SDL_SCANCODE_KP_COLON = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_COLON); pub const SDL_SCANCODE_KP_HASH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_HASH); pub const SDL_SCANCODE_KP_SPACE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_SPACE); pub const SDL_SCANCODE_KP_AT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_AT); pub const SDL_SCANCODE_KP_EXCLAM = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_EXCLAM); pub const SDL_SCANCODE_KP_MEMSTORE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MEMSTORE); pub const SDL_SCANCODE_KP_MEMRECALL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MEMRECALL); pub const SDL_SCANCODE_KP_MEMCLEAR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MEMCLEAR); pub const SDL_SCANCODE_KP_MEMADD = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MEMADD); pub const SDL_SCANCODE_KP_MEMSUBTRACT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MEMSUBTRACT); pub const SDL_SCANCODE_KP_MEMMULTIPLY = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MEMMULTIPLY); pub const SDL_SCANCODE_KP_MEMDIVIDE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_MEMDIVIDE); pub const SDL_SCANCODE_KP_PLUSMINUS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_PLUSMINUS); pub const SDL_SCANCODE_KP_CLEAR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_CLEAR); pub const SDL_SCANCODE_KP_CLEARENTRY = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_CLEARENTRY); pub const SDL_SCANCODE_KP_BINARY = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_BINARY); pub const SDL_SCANCODE_KP_OCTAL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_OCTAL); pub const SDL_SCANCODE_KP_DECIMAL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_DECIMAL); pub const SDL_SCANCODE_KP_HEXADECIMAL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KP_HEXADECIMAL); pub const SDL_SCANCODE_LCTRL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LCTRL); pub const SDL_SCANCODE_LSHIFT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LSHIFT); pub const SDL_SCANCODE_LALT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LALT); pub const SDL_SCANCODE_LGUI = @enumToInt(enum_unnamed_33.SDL_SCANCODE_LGUI); pub const SDL_SCANCODE_RCTRL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RCTRL); pub const SDL_SCANCODE_RSHIFT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RSHIFT); pub const SDL_SCANCODE_RALT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RALT); pub const SDL_SCANCODE_RGUI = @enumToInt(enum_unnamed_33.SDL_SCANCODE_RGUI); pub const SDL_SCANCODE_MODE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_MODE); pub const SDL_SCANCODE_AUDIONEXT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AUDIONEXT); pub const SDL_SCANCODE_AUDIOPREV = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AUDIOPREV); pub const SDL_SCANCODE_AUDIOSTOP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AUDIOSTOP); pub const SDL_SCANCODE_AUDIOPLAY = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AUDIOPLAY); pub const SDL_SCANCODE_AUDIOMUTE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AUDIOMUTE); pub const SDL_SCANCODE_MEDIASELECT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_MEDIASELECT); pub const SDL_SCANCODE_WWW = @enumToInt(enum_unnamed_33.SDL_SCANCODE_WWW); pub const SDL_SCANCODE_MAIL = @enumToInt(enum_unnamed_33.SDL_SCANCODE_MAIL); pub const SDL_SCANCODE_CALCULATOR = @enumToInt(enum_unnamed_33.SDL_SCANCODE_CALCULATOR); pub const SDL_SCANCODE_COMPUTER = @enumToInt(enum_unnamed_33.SDL_SCANCODE_COMPUTER); pub const SDL_SCANCODE_AC_SEARCH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AC_SEARCH); pub const SDL_SCANCODE_AC_HOME = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AC_HOME); pub const SDL_SCANCODE_AC_BACK = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AC_BACK); pub const SDL_SCANCODE_AC_FORWARD = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AC_FORWARD); pub const SDL_SCANCODE_AC_STOP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AC_STOP); pub const SDL_SCANCODE_AC_REFRESH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AC_REFRESH); pub const SDL_SCANCODE_AC_BOOKMARKS = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AC_BOOKMARKS); pub const SDL_SCANCODE_BRIGHTNESSDOWN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_BRIGHTNESSDOWN); pub const SDL_SCANCODE_BRIGHTNESSUP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_BRIGHTNESSUP); pub const SDL_SCANCODE_DISPLAYSWITCH = @enumToInt(enum_unnamed_33.SDL_SCANCODE_DISPLAYSWITCH); pub const SDL_SCANCODE_KBDILLUMTOGGLE = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KBDILLUMTOGGLE); pub const SDL_SCANCODE_KBDILLUMDOWN = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KBDILLUMDOWN); pub const SDL_SCANCODE_KBDILLUMUP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_KBDILLUMUP); pub const SDL_SCANCODE_EJECT = @enumToInt(enum_unnamed_33.SDL_SCANCODE_EJECT); pub const SDL_SCANCODE_SLEEP = @enumToInt(enum_unnamed_33.SDL_SCANCODE_SLEEP); pub const SDL_SCANCODE_APP1 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_APP1); pub const SDL_SCANCODE_APP2 = @enumToInt(enum_unnamed_33.SDL_SCANCODE_APP2); pub const SDL_SCANCODE_AUDIOREWIND = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AUDIOREWIND); pub const SDL_SCANCODE_AUDIOFASTFORWARD = @enumToInt(enum_unnamed_33.SDL_SCANCODE_AUDIOFASTFORWARD); pub const SDL_NUM_SCANCODES = @enumToInt(enum_unnamed_33.SDL_NUM_SCANCODES); const enum_unnamed_33 = extern enum(c_int) { SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, SDL_SCANCODE_NONUSHASH = 50, SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, SDL_SCANCODE_APPLICATION = 101, SDL_SCANCODE_POWER = 102, SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, SDL_SCANCODE_LANG2 = 145, SDL_SCANCODE_LANG3 = 146, SDL_SCANCODE_LANG4 = 147, SDL_SCANCODE_LANG5 = 148, SDL_SCANCODE_LANG6 = 149, SDL_SCANCODE_LANG7 = 150, SDL_SCANCODE_LANG8 = 151, SDL_SCANCODE_LANG9 = 152, SDL_SCANCODE_ALTERASE = 153, SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, SDL_SCANCODE_LGUI = 227, SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, SDL_SCANCODE_RGUI = 231, SDL_SCANCODE_MODE = 257, SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, SDL_SCANCODE_AUDIOREWIND = 285, SDL_SCANCODE_AUDIOFASTFORWARD = 286, SDL_NUM_SCANCODES = 512, _, }; pub const SDL_Scancode = enum_unnamed_33; pub const SDL_Keycode = i32; pub const SDLK_UNKNOWN = @enumToInt(enum_unnamed_34.SDLK_UNKNOWN); pub const SDLK_RETURN = @enumToInt(enum_unnamed_34.SDLK_RETURN); pub const SDLK_ESCAPE = @enumToInt(enum_unnamed_34.SDLK_ESCAPE); pub const SDLK_BACKSPACE = @enumToInt(enum_unnamed_34.SDLK_BACKSPACE); pub const SDLK_TAB = @enumToInt(enum_unnamed_34.SDLK_TAB); pub const SDLK_SPACE = @enumToInt(enum_unnamed_34.SDLK_SPACE); pub const SDLK_EXCLAIM = @enumToInt(enum_unnamed_34.SDLK_EXCLAIM); pub const SDLK_QUOTEDBL = @enumToInt(enum_unnamed_34.SDLK_QUOTEDBL); pub const SDLK_HASH = @enumToInt(enum_unnamed_34.SDLK_HASH); pub const SDLK_PERCENT = @enumToInt(enum_unnamed_34.SDLK_PERCENT); pub const SDLK_DOLLAR = @enumToInt(enum_unnamed_34.SDLK_DOLLAR); pub const SDLK_AMPERSAND = @enumToInt(enum_unnamed_34.SDLK_AMPERSAND); pub const SDLK_QUOTE = @enumToInt(enum_unnamed_34.SDLK_QUOTE); pub const SDLK_LEFTPAREN = @enumToInt(enum_unnamed_34.SDLK_LEFTPAREN); pub const SDLK_RIGHTPAREN = @enumToInt(enum_unnamed_34.SDLK_RIGHTPAREN); pub const SDLK_ASTERISK = @enumToInt(enum_unnamed_34.SDLK_ASTERISK); pub const SDLK_PLUS = @enumToInt(enum_unnamed_34.SDLK_PLUS); pub const SDLK_COMMA = @enumToInt(enum_unnamed_34.SDLK_COMMA); pub const SDLK_MINUS = @enumToInt(enum_unnamed_34.SDLK_MINUS); pub const SDLK_PERIOD = @enumToInt(enum_unnamed_34.SDLK_PERIOD); pub const SDLK_SLASH = @enumToInt(enum_unnamed_34.SDLK_SLASH); pub const SDLK_0 = @enumToInt(enum_unnamed_34.SDLK_0); pub const SDLK_1 = @enumToInt(enum_unnamed_34.SDLK_1); pub const SDLK_2 = @enumToInt(enum_unnamed_34.SDLK_2); pub const SDLK_3 = @enumToInt(enum_unnamed_34.SDLK_3); pub const SDLK_4 = @enumToInt(enum_unnamed_34.SDLK_4); pub const SDLK_5 = @enumToInt(enum_unnamed_34.SDLK_5); pub const SDLK_6 = @enumToInt(enum_unnamed_34.SDLK_6); pub const SDLK_7 = @enumToInt(enum_unnamed_34.SDLK_7); pub const SDLK_8 = @enumToInt(enum_unnamed_34.SDLK_8); pub const SDLK_9 = @enumToInt(enum_unnamed_34.SDLK_9); pub const SDLK_COLON = @enumToInt(enum_unnamed_34.SDLK_COLON); pub const SDLK_SEMICOLON = @enumToInt(enum_unnamed_34.SDLK_SEMICOLON); pub const SDLK_LESS = @enumToInt(enum_unnamed_34.SDLK_LESS); pub const SDLK_EQUALS = @enumToInt(enum_unnamed_34.SDLK_EQUALS); pub const SDLK_GREATER = @enumToInt(enum_unnamed_34.SDLK_GREATER); pub const SDLK_QUESTION = @enumToInt(enum_unnamed_34.SDLK_QUESTION); pub const SDLK_AT = @enumToInt(enum_unnamed_34.SDLK_AT); pub const SDLK_LEFTBRACKET = @enumToInt(enum_unnamed_34.SDLK_LEFTBRACKET); pub const SDLK_BACKSLASH = @enumToInt(enum_unnamed_34.SDLK_BACKSLASH); pub const SDLK_RIGHTBRACKET = @enumToInt(enum_unnamed_34.SDLK_RIGHTBRACKET); pub const SDLK_CARET = @enumToInt(enum_unnamed_34.SDLK_CARET); pub const SDLK_UNDERSCORE = @enumToInt(enum_unnamed_34.SDLK_UNDERSCORE); pub const SDLK_BACKQUOTE = @enumToInt(enum_unnamed_34.SDLK_BACKQUOTE); pub const SDLK_a = @enumToInt(enum_unnamed_34.SDLK_a); pub const SDLK_b = @enumToInt(enum_unnamed_34.SDLK_b); pub const SDLK_c = @enumToInt(enum_unnamed_34.SDLK_c); pub const SDLK_d = @enumToInt(enum_unnamed_34.SDLK_d); pub const SDLK_e = @enumToInt(enum_unnamed_34.SDLK_e); pub const SDLK_f = @enumToInt(enum_unnamed_34.SDLK_f); pub const SDLK_g = @enumToInt(enum_unnamed_34.SDLK_g); pub const SDLK_h = @enumToInt(enum_unnamed_34.SDLK_h); pub const SDLK_i = @enumToInt(enum_unnamed_34.SDLK_i); pub const SDLK_j = @enumToInt(enum_unnamed_34.SDLK_j); pub const SDLK_k = @enumToInt(enum_unnamed_34.SDLK_k); pub const SDLK_l = @enumToInt(enum_unnamed_34.SDLK_l); pub const SDLK_m = @enumToInt(enum_unnamed_34.SDLK_m); pub const SDLK_n = @enumToInt(enum_unnamed_34.SDLK_n); pub const SDLK_o = @enumToInt(enum_unnamed_34.SDLK_o); pub const SDLK_p = @enumToInt(enum_unnamed_34.SDLK_p); pub const SDLK_q = @enumToInt(enum_unnamed_34.SDLK_q); pub const SDLK_r = @enumToInt(enum_unnamed_34.SDLK_r); pub const SDLK_s = @enumToInt(enum_unnamed_34.SDLK_s); pub const SDLK_u = @enumToInt(enum_unnamed_34.SDLK_u); pub const SDLK_v = @enumToInt(enum_unnamed_34.SDLK_v); pub const SDLK_w = @enumToInt(enum_unnamed_34.SDLK_w); pub const SDLK_x = @enumToInt(enum_unnamed_34.SDLK_x); pub const SDLK_y = @enumToInt(enum_unnamed_34.SDLK_y); pub const SDLK_z = @enumToInt(enum_unnamed_34.SDLK_z); pub const SDLK_CAPSLOCK = @enumToInt(enum_unnamed_34.SDLK_CAPSLOCK); pub const SDLK_F1 = @enumToInt(enum_unnamed_34.SDLK_F1); pub const SDLK_F2 = @enumToInt(enum_unnamed_34.SDLK_F2); pub const SDLK_F3 = @enumToInt(enum_unnamed_34.SDLK_F3); pub const SDLK_F4 = @enumToInt(enum_unnamed_34.SDLK_F4); pub const SDLK_F5 = @enumToInt(enum_unnamed_34.SDLK_F5); pub const SDLK_F6 = @enumToInt(enum_unnamed_34.SDLK_F6); pub const SDLK_F7 = @enumToInt(enum_unnamed_34.SDLK_F7); pub const SDLK_F8 = @enumToInt(enum_unnamed_34.SDLK_F8); pub const SDLK_F9 = @enumToInt(enum_unnamed_34.SDLK_F9); pub const SDLK_F10 = @enumToInt(enum_unnamed_34.SDLK_F10); pub const SDLK_F11 = @enumToInt(enum_unnamed_34.SDLK_F11); pub const SDLK_F12 = @enumToInt(enum_unnamed_34.SDLK_F12); pub const SDLK_PRINTSCREEN = @enumToInt(enum_unnamed_34.SDLK_PRINTSCREEN); pub const SDLK_SCROLLLOCK = @enumToInt(enum_unnamed_34.SDLK_SCROLLLOCK); pub const SDLK_PAUSE = @enumToInt(enum_unnamed_34.SDLK_PAUSE); pub const SDLK_INSERT = @enumToInt(enum_unnamed_34.SDLK_INSERT); pub const SDLK_HOME = @enumToInt(enum_unnamed_34.SDLK_HOME); pub const SDLK_PAGEUP = @enumToInt(enum_unnamed_34.SDLK_PAGEUP); pub const SDLK_DELETE = @enumToInt(enum_unnamed_34.SDLK_DELETE); pub const SDLK_END = @enumToInt(enum_unnamed_34.SDLK_END); pub const SDLK_PAGEDOWN = @enumToInt(enum_unnamed_34.SDLK_PAGEDOWN); pub const SDLK_RIGHT = @enumToInt(enum_unnamed_34.SDLK_RIGHT); pub const SDLK_LEFT = @enumToInt(enum_unnamed_34.SDLK_LEFT); pub const SDLK_DOWN = @enumToInt(enum_unnamed_34.SDLK_DOWN); pub const SDLK_UP = @enumToInt(enum_unnamed_34.SDLK_UP); pub const SDLK_NUMLOCKCLEAR = @enumToInt(enum_unnamed_34.SDLK_NUMLOCKCLEAR); pub const SDLK_KP_DIVIDE = @enumToInt(enum_unnamed_34.SDLK_KP_DIVIDE); pub const SDLK_KP_MULTIPLY = @enumToInt(enum_unnamed_34.SDLK_KP_MULTIPLY); pub const SDLK_KP_MINUS = @enumToInt(enum_unnamed_34.SDLK_KP_MINUS); pub const SDLK_KP_PLUS = @enumToInt(enum_unnamed_34.SDLK_KP_PLUS); pub const SDLK_KP_ENTER = @enumToInt(enum_unnamed_34.SDLK_KP_ENTER); pub const SDLK_KP_1 = @enumToInt(enum_unnamed_34.SDLK_KP_1); pub const SDLK_KP_2 = @enumToInt(enum_unnamed_34.SDLK_KP_2); pub const SDLK_KP_3 = @enumToInt(enum_unnamed_34.SDLK_KP_3); pub const SDLK_KP_4 = @enumToInt(enum_unnamed_34.SDLK_KP_4); pub const SDLK_KP_5 = @enumToInt(enum_unnamed_34.SDLK_KP_5); pub const SDLK_KP_6 = @enumToInt(enum_unnamed_34.SDLK_KP_6); pub const SDLK_KP_7 = @enumToInt(enum_unnamed_34.SDLK_KP_7); pub const SDLK_KP_8 = @enumToInt(enum_unnamed_34.SDLK_KP_8); pub const SDLK_KP_9 = @enumToInt(enum_unnamed_34.SDLK_KP_9); pub const SDLK_KP_0 = @enumToInt(enum_unnamed_34.SDLK_KP_0); pub const SDLK_KP_PERIOD = @enumToInt(enum_unnamed_34.SDLK_KP_PERIOD); pub const SDLK_APPLICATION = @enumToInt(enum_unnamed_34.SDLK_APPLICATION); pub const SDLK_POWER = @enumToInt(enum_unnamed_34.SDLK_POWER); pub const SDLK_KP_EQUALS = @enumToInt(enum_unnamed_34.SDLK_KP_EQUALS); pub const SDLK_F13 = @enumToInt(enum_unnamed_34.SDLK_F13); pub const SDLK_F14 = @enumToInt(enum_unnamed_34.SDLK_F14); pub const SDLK_F15 = @enumToInt(enum_unnamed_34.SDLK_F15); pub const SDLK_F16 = @enumToInt(enum_unnamed_34.SDLK_F16); pub const SDLK_F17 = @enumToInt(enum_unnamed_34.SDLK_F17); pub const SDLK_F18 = @enumToInt(enum_unnamed_34.SDLK_F18); pub const SDLK_F19 = @enumToInt(enum_unnamed_34.SDLK_F19); pub const SDLK_F20 = @enumToInt(enum_unnamed_34.SDLK_F20); pub const SDLK_F21 = @enumToInt(enum_unnamed_34.SDLK_F21); pub const SDLK_F22 = @enumToInt(enum_unnamed_34.SDLK_F22); pub const SDLK_F23 = @enumToInt(enum_unnamed_34.SDLK_F23); pub const SDLK_F24 = @enumToInt(enum_unnamed_34.SDLK_F24); pub const SDLK_EXECUTE = @enumToInt(enum_unnamed_34.SDLK_EXECUTE); pub const SDLK_HELP = @enumToInt(enum_unnamed_34.SDLK_HELP); pub const SDLK_MENU = @enumToInt(enum_unnamed_34.SDLK_MENU); pub const SDLK_SELECT = @enumToInt(enum_unnamed_34.SDLK_SELECT); pub const SDLK_STOP = @enumToInt(enum_unnamed_34.SDLK_STOP); pub const SDLK_AGAIN = @enumToInt(enum_unnamed_34.SDLK_AGAIN); pub const SDLK_UNDO = @enumToInt(enum_unnamed_34.SDLK_UNDO); pub const SDLK_CUT = @enumToInt(enum_unnamed_34.SDLK_CUT); pub const SDLK_COPY = @enumToInt(enum_unnamed_34.SDLK_COPY); pub const SDLK_PASTE = @enumToInt(enum_unnamed_34.SDLK_PASTE); pub const SDLK_FIND = @enumToInt(enum_unnamed_34.SDLK_FIND); pub const SDLK_MUTE = @enumToInt(enum_unnamed_34.SDLK_MUTE); pub const SDLK_VOLUMEUP = @enumToInt(enum_unnamed_34.SDLK_VOLUMEUP); pub const SDLK_VOLUMEDOWN = @enumToInt(enum_unnamed_34.SDLK_VOLUMEDOWN); pub const SDLK_KP_COMMA = @enumToInt(enum_unnamed_34.SDLK_KP_COMMA); pub const SDLK_KP_EQUALSAS400 = @enumToInt(enum_unnamed_34.SDLK_KP_EQUALSAS400); pub const SDLK_ALTERASE = @enumToInt(enum_unnamed_34.SDLK_ALTERASE); pub const SDLK_SYSREQ = @enumToInt(enum_unnamed_34.SDLK_SYSREQ); pub const SDLK_CANCEL = @enumToInt(enum_unnamed_34.SDLK_CANCEL); pub const SDLK_CLEAR = @enumToInt(enum_unnamed_34.SDLK_CLEAR); pub const SDLK_PRIOR = @enumToInt(enum_unnamed_34.SDLK_PRIOR); pub const SDLK_RETURN2 = @enumToInt(enum_unnamed_34.SDLK_RETURN2); pub const SDLK_SEPARATOR = @enumToInt(enum_unnamed_34.SDLK_SEPARATOR); pub const SDLK_OUT = @enumToInt(enum_unnamed_34.SDLK_OUT); pub const SDLK_OPER = @enumToInt(enum_unnamed_34.SDLK_OPER); pub const SDLK_CLEARAGAIN = @enumToInt(enum_unnamed_34.SDLK_CLEARAGAIN); pub const SDLK_CRSEL = @enumToInt(enum_unnamed_34.SDLK_CRSEL); pub const SDLK_EXSEL = @enumToInt(enum_unnamed_34.SDLK_EXSEL); pub const SDLK_KP_00 = @enumToInt(enum_unnamed_34.SDLK_KP_00); pub const SDLK_KP_000 = @enumToInt(enum_unnamed_34.SDLK_KP_000); pub const SDLK_THOUSANDSSEPARATOR = @enumToInt(enum_unnamed_34.SDLK_THOUSANDSSEPARATOR); pub const SDLK_DECIMALSEPARATOR = @enumToInt(enum_unnamed_34.SDLK_DECIMALSEPARATOR); pub const SDLK_CURRENCYUNIT = @enumToInt(enum_unnamed_34.SDLK_CURRENCYUNIT); pub const SDLK_CURRENCYSUBUNIT = @enumToInt(enum_unnamed_34.SDLK_CURRENCYSUBUNIT); pub const SDLK_KP_LEFTPAREN = @enumToInt(enum_unnamed_34.SDLK_KP_LEFTPAREN); pub const SDLK_KP_RIGHTPAREN = @enumToInt(enum_unnamed_34.SDLK_KP_RIGHTPAREN); pub const SDLK_KP_LEFTBRACE = @enumToInt(enum_unnamed_34.SDLK_KP_LEFTBRACE); pub const SDLK_KP_RIGHTBRACE = @enumToInt(enum_unnamed_34.SDLK_KP_RIGHTBRACE); pub const SDLK_KP_TAB = @enumToInt(enum_unnamed_34.SDLK_KP_TAB); pub const SDLK_KP_BACKSPACE = @enumToInt(enum_unnamed_34.SDLK_KP_BACKSPACE); pub const SDLK_KP_A = @enumToInt(enum_unnamed_34.SDLK_KP_A); pub const SDLK_KP_B = @enumToInt(enum_unnamed_34.SDLK_KP_B); pub const SDLK_KP_C = @enumToInt(enum_unnamed_34.SDLK_KP_C); pub const SDLK_KP_D = @enumToInt(enum_unnamed_34.SDLK_KP_D); pub const SDLK_KP_E = @enumToInt(enum_unnamed_34.SDLK_KP_E); pub const SDLK_KP_F = @enumToInt(enum_unnamed_34.SDLK_KP_F); pub const SDLK_KP_XOR = @enumToInt(enum_unnamed_34.SDLK_KP_XOR); pub const SDLK_KP_POWER = @enumToInt(enum_unnamed_34.SDLK_KP_POWER); pub const SDLK_KP_PERCENT = @enumToInt(enum_unnamed_34.SDLK_KP_PERCENT); pub const SDLK_KP_LESS = @enumToInt(enum_unnamed_34.SDLK_KP_LESS); pub const SDLK_KP_GREATER = @enumToInt(enum_unnamed_34.SDLK_KP_GREATER); pub const SDLK_KP_AMPERSAND = @enumToInt(enum_unnamed_34.SDLK_KP_AMPERSAND); pub const SDLK_KP_DBLAMPERSAND = @enumToInt(enum_unnamed_34.SDLK_KP_DBLAMPERSAND); pub const SDLK_KP_VERTICALBAR = @enumToInt(enum_unnamed_34.SDLK_KP_VERTICALBAR); pub const SDLK_KP_DBLVERTICALBAR = @enumToInt(enum_unnamed_34.SDLK_KP_DBLVERTICALBAR); pub const SDLK_KP_COLON = @enumToInt(enum_unnamed_34.SDLK_KP_COLON); pub const SDLK_KP_HASH = @enumToInt(enum_unnamed_34.SDLK_KP_HASH); pub const SDLK_KP_SPACE = @enumToInt(enum_unnamed_34.SDLK_KP_SPACE); pub const SDLK_KP_AT = @enumToInt(enum_unnamed_34.SDLK_KP_AT); pub const SDLK_KP_EXCLAM = @enumToInt(enum_unnamed_34.SDLK_KP_EXCLAM); pub const SDLK_KP_MEMSTORE = @enumToInt(enum_unnamed_34.SDLK_KP_MEMSTORE); pub const SDLK_KP_MEMRECALL = @enumToInt(enum_unnamed_34.SDLK_KP_MEMRECALL); pub const SDLK_KP_MEMCLEAR = @enumToInt(enum_unnamed_34.SDLK_KP_MEMCLEAR); pub const SDLK_KP_MEMADD = @enumToInt(enum_unnamed_34.SDLK_KP_MEMADD); pub const SDLK_KP_MEMSUBTRACT = @enumToInt(enum_unnamed_34.SDLK_KP_MEMSUBTRACT); pub const SDLK_KP_MEMMULTIPLY = @enumToInt(enum_unnamed_34.SDLK_KP_MEMMULTIPLY); pub const SDLK_KP_MEMDIVIDE = @enumToInt(enum_unnamed_34.SDLK_KP_MEMDIVIDE); pub const SDLK_KP_PLUSMINUS = @enumToInt(enum_unnamed_34.SDLK_KP_PLUSMINUS); pub const SDLK_KP_CLEAR = @enumToInt(enum_unnamed_34.SDLK_KP_CLEAR); pub const SDLK_KP_CLEARENTRY = @enumToInt(enum_unnamed_34.SDLK_KP_CLEARENTRY); pub const SDLK_KP_BINARY = @enumToInt(enum_unnamed_34.SDLK_KP_BINARY); pub const SDLK_KP_OCTAL = @enumToInt(enum_unnamed_34.SDLK_KP_OCTAL); pub const SDLK_KP_DECIMAL = @enumToInt(enum_unnamed_34.SDLK_KP_DECIMAL); pub const SDLK_KP_HEXADECIMAL = @enumToInt(enum_unnamed_34.SDLK_KP_HEXADECIMAL); pub const SDLK_LCTRL = @enumToInt(enum_unnamed_34.SDLK_LCTRL); pub const SDLK_LSHIFT = @enumToInt(enum_unnamed_34.SDLK_LSHIFT); pub const SDLK_LALT = @enumToInt(enum_unnamed_34.SDLK_LALT); pub const SDLK_LGUI = @enumToInt(enum_unnamed_34.SDLK_LGUI); pub const SDLK_RCTRL = @enumToInt(enum_unnamed_34.SDLK_RCTRL); pub const SDLK_RSHIFT = @enumToInt(enum_unnamed_34.SDLK_RSHIFT); pub const SDLK_RALT = @enumToInt(enum_unnamed_34.SDLK_RALT); pub const SDLK_RGUI = @enumToInt(enum_unnamed_34.SDLK_RGUI); pub const SDLK_MODE = @enumToInt(enum_unnamed_34.SDLK_MODE); pub const SDLK_AUDIONEXT = @enumToInt(enum_unnamed_34.SDLK_AUDIONEXT); pub const SDLK_AUDIOPREV = @enumToInt(enum_unnamed_34.SDLK_AUDIOPREV); pub const SDLK_AUDIOSTOP = @enumToInt(enum_unnamed_34.SDLK_AUDIOSTOP); pub const SDLK_AUDIOPLAY = @enumToInt(enum_unnamed_34.SDLK_AUDIOPLAY); pub const SDLK_AUDIOMUTE = @enumToInt(enum_unnamed_34.SDLK_AUDIOMUTE); pub const SDLK_MEDIASELECT = @enumToInt(enum_unnamed_34.SDLK_MEDIASELECT); pub const SDLK_WWW = @enumToInt(enum_unnamed_34.SDLK_WWW); pub const SDLK_MAIL = @enumToInt(enum_unnamed_34.SDLK_MAIL); pub const SDLK_CALCULATOR = @enumToInt(enum_unnamed_34.SDLK_CALCULATOR); pub const SDLK_COMPUTER = @enumToInt(enum_unnamed_34.SDLK_COMPUTER); pub const SDLK_AC_SEARCH = @enumToInt(enum_unnamed_34.SDLK_AC_SEARCH); pub const SDLK_AC_HOME = @enumToInt(enum_unnamed_34.SDLK_AC_HOME); pub const SDLK_AC_BACK = @enumToInt(enum_unnamed_34.SDLK_AC_BACK); pub const SDLK_AC_FORWARD = @enumToInt(enum_unnamed_34.SDLK_AC_FORWARD); pub const SDLK_AC_STOP = @enumToInt(enum_unnamed_34.SDLK_AC_STOP); pub const SDLK_AC_REFRESH = @enumToInt(enum_unnamed_34.SDLK_AC_REFRESH); pub const SDLK_AC_BOOKMARKS = @enumToInt(enum_unnamed_34.SDLK_AC_BOOKMARKS); pub const SDLK_BRIGHTNESSDOWN = @enumToInt(enum_unnamed_34.SDLK_BRIGHTNESSDOWN); pub const SDLK_BRIGHTNESSUP = @enumToInt(enum_unnamed_34.SDLK_BRIGHTNESSUP); pub const SDLK_DISPLAYSWITCH = @enumToInt(enum_unnamed_34.SDLK_DISPLAYSWITCH); pub const SDLK_KBDILLUMTOGGLE = @enumToInt(enum_unnamed_34.SDLK_KBDILLUMTOGGLE); pub const SDLK_KBDILLUMDOWN = @enumToInt(enum_unnamed_34.SDLK_KBDILLUMDOWN); pub const SDLK_KBDILLUMUP = @enumToInt(enum_unnamed_34.SDLK_KBDILLUMUP); pub const SDLK_EJECT = @enumToInt(enum_unnamed_34.SDLK_EJECT); pub const SDLK_SLEEP = @enumToInt(enum_unnamed_34.SDLK_SLEEP); pub const SDLK_APP1 = @enumToInt(enum_unnamed_34.SDLK_APP1); pub const SDLK_APP2 = @enumToInt(enum_unnamed_34.SDLK_APP2); pub const SDLK_AUDIOREWIND = @enumToInt(enum_unnamed_34.SDLK_AUDIOREWIND); pub const SDLK_AUDIOFASTFORWARD = @enumToInt(enum_unnamed_34.SDLK_AUDIOFASTFORWARD); const enum_unnamed_34 = extern enum(c_int) { SDLK_UNKNOWN = 0, SDLK_RETURN = 13, SDLK_ESCAPE = 27, SDLK_BACKSPACE = 8, SDLK_TAB = 9, SDLK_SPACE = 32, SDLK_EXCLAIM = 33, SDLK_QUOTEDBL = 34, SDLK_HASH = 35, SDLK_PERCENT = 37, SDLK_DOLLAR = 36, SDLK_AMPERSAND = 38, SDLK_QUOTE = 39, SDLK_LEFTPAREN = 40, SDLK_RIGHTPAREN = 41, SDLK_ASTERISK = 42, SDLK_PLUS = 43, SDLK_COMMA = 44, SDLK_MINUS = 45, SDLK_PERIOD = 46, SDLK_SLASH = 47, SDLK_0 = 48, SDLK_1 = 49, SDLK_2 = 50, SDLK_3 = 51, SDLK_4 = 52, SDLK_5 = 53, SDLK_6 = 54, SDLK_7 = 55, SDLK_8 = 56, SDLK_9 = 57, SDLK_COLON = 58, SDLK_SEMICOLON = 59, SDLK_LESS = 60, SDLK_EQUALS = 61, SDLK_GREATER = 62, SDLK_QUESTION = 63, SDLK_AT = 64, SDLK_LEFTBRACKET = 91, SDLK_BACKSLASH = 92, SDLK_RIGHTBRACKET = 93, SDLK_CARET = 94, SDLK_UNDERSCORE = 95, SDLK_BACKQUOTE = 96, SDLK_a = 97, SDLK_b = 98, SDLK_c = 99, SDLK_d = 100, SDLK_e = 101, SDLK_f = 102, SDLK_g = 103, SDLK_h = 104, SDLK_i = 105, SDLK_j = 106, SDLK_k = 107, SDLK_l = 108, SDLK_m = 109, SDLK_n = 110, SDLK_o = 111, SDLK_p = 112, SDLK_q = 113, SDLK_r = 114, SDLK_s = 115, SDLK_u = 117, SDLK_v = 118, SDLK_w = 119, SDLK_x = 120, SDLK_y = 121, SDLK_z = 122, SDLK_CAPSLOCK = 1073741881, SDLK_F1 = 1073741882, SDLK_F2 = 1073741883, SDLK_F3 = 1073741884, SDLK_F4 = 1073741885, SDLK_F5 = 1073741886, SDLK_F6 = 1073741887, SDLK_F7 = 1073741888, SDLK_F8 = 1073741889, SDLK_F9 = 1073741890, SDLK_F10 = 1073741891, SDLK_F11 = 1073741892, SDLK_F12 = 1073741893, SDLK_PRINTSCREEN = 1073741894, SDLK_SCROLLLOCK = 1073741895, SDLK_PAUSE = 1073741896, SDLK_INSERT = 1073741897, SDLK_HOME = 1073741898, SDLK_PAGEUP = 1073741899, SDLK_DELETE = 127, SDLK_END = 1073741901, SDLK_PAGEDOWN = 1073741902, SDLK_RIGHT = 1073741903, SDLK_LEFT = 1073741904, SDLK_DOWN = 1073741905, SDLK_UP = 1073741906, SDLK_NUMLOCKCLEAR = 1073741907, SDLK_KP_DIVIDE = 1073741908, SDLK_KP_MULTIPLY = 1073741909, SDLK_KP_MINUS = 1073741910, SDLK_KP_PLUS = 1073741911, SDLK_KP_ENTER = 1073741912, SDLK_KP_1 = 1073741913, SDLK_KP_2 = 1073741914, SDLK_KP_3 = 1073741915, SDLK_KP_4 = 1073741916, SDLK_KP_5 = 1073741917, SDLK_KP_6 = 1073741918, SDLK_KP_7 = 1073741919, SDLK_KP_8 = 1073741920, SDLK_KP_9 = 1073741921, SDLK_KP_0 = 1073741922, SDLK_KP_PERIOD = 1073741923, SDLK_APPLICATION = 1073741925, SDLK_POWER = 1073741926, SDLK_KP_EQUALS = 1073741927, SDLK_F13 = 1073741928, SDLK_F14 = 1073741929, SDLK_F15 = 1073741930, SDLK_F16 = 1073741931, SDLK_F17 = 1073741932, SDLK_F18 = 1073741933, SDLK_F19 = 1073741934, SDLK_F20 = 1073741935, SDLK_F21 = 1073741936, SDLK_F22 = 1073741937, SDLK_F23 = 1073741938, SDLK_F24 = 1073741939, SDLK_EXECUTE = 1073741940, SDLK_HELP = 1073741941, SDLK_MENU = 1073741942, SDLK_SELECT = 1073741943, SDLK_STOP = 1073741944, SDLK_AGAIN = 1073741945, SDLK_UNDO = 1073741946, SDLK_CUT = 1073741947, SDLK_COPY = 1073741948, SDLK_PASTE = 1073741949, SDLK_FIND = 1073741950, SDLK_MUTE = 1073741951, SDLK_VOLUMEUP = 1073741952, SDLK_VOLUMEDOWN = 1073741953, SDLK_KP_COMMA = 1073741957, SDLK_KP_EQUALSAS400 = 1073741958, SDLK_ALTERASE = 1073741977, SDLK_SYSREQ = 1073741978, SDLK_CANCEL = 1073741979, SDLK_CLEAR = 1073741980, SDLK_PRIOR = 1073741981, SDLK_RETURN2 = 1073741982, SDLK_SEPARATOR = 1073741983, SDLK_OUT = 1073741984, SDLK_OPER = 1073741985, SDLK_CLEARAGAIN = 1073741986, SDLK_CRSEL = 1073741987, SDLK_EXSEL = 1073741988, SDLK_KP_00 = 1073742000, SDLK_KP_000 = 1073742001, SDLK_THOUSANDSSEPARATOR = 1073742002, SDLK_DECIMALSEPARATOR = 1073742003, SDLK_CURRENCYUNIT = 1073742004, SDLK_CURRENCYSUBUNIT = 1073742005, SDLK_KP_LEFTPAREN = 1073742006, SDLK_KP_RIGHTPAREN = 1073742007, SDLK_KP_LEFTBRACE = 1073742008, SDLK_KP_RIGHTBRACE = 1073742009, SDLK_KP_TAB = 1073742010, SDLK_KP_BACKSPACE = 1073742011, SDLK_KP_A = 1073742012, SDLK_KP_B = 1073742013, SDLK_KP_C = 1073742014, SDLK_KP_D = 1073742015, SDLK_KP_E = 1073742016, SDLK_KP_F = 1073742017, SDLK_KP_XOR = 1073742018, SDLK_KP_POWER = 1073742019, SDLK_KP_PERCENT = 1073742020, SDLK_KP_LESS = 1073742021, SDLK_KP_GREATER = 1073742022, SDLK_KP_AMPERSAND = 1073742023, SDLK_KP_DBLAMPERSAND = 1073742024, SDLK_KP_VERTICALBAR = 1073742025, SDLK_KP_DBLVERTICALBAR = 1073742026, SDLK_KP_COLON = 1073742027, SDLK_KP_HASH = 1073742028, SDLK_KP_SPACE = 1073742029, SDLK_KP_AT = 1073742030, SDLK_KP_EXCLAM = 1073742031, SDLK_KP_MEMSTORE = 1073742032, SDLK_KP_MEMRECALL = 1073742033, SDLK_KP_MEMCLEAR = 1073742034, SDLK_KP_MEMADD = 1073742035, SDLK_KP_MEMSUBTRACT = 1073742036, SDLK_KP_MEMMULTIPLY = 1073742037, SDLK_KP_MEMDIVIDE = 1073742038, SDLK_KP_PLUSMINUS = 1073742039, SDLK_KP_CLEAR = 1073742040, SDLK_KP_CLEARENTRY = 1073742041, SDLK_KP_BINARY = 1073742042, SDLK_KP_OCTAL = 1073742043, SDLK_KP_DECIMAL = 1073742044, SDLK_KP_HEXADECIMAL = 1073742045, SDLK_LCTRL = 1073742048, SDLK_LSHIFT = 1073742049, SDLK_LALT = 1073742050, SDLK_LGUI = 1073742051, SDLK_RCTRL = 1073742052, SDLK_RSHIFT = 1073742053, SDLK_RALT = 1073742054, SDLK_RGUI = 1073742055, SDLK_MODE = 1073742081, SDLK_AUDIONEXT = 1073742082, SDLK_AUDIOPREV = 1073742083, SDLK_AUDIOSTOP = 1073742084, SDLK_AUDIOPLAY = 1073742085, SDLK_AUDIOMUTE = 1073742086, SDLK_MEDIASELECT = 1073742087, SDLK_WWW = 1073742088, SDLK_MAIL = 1073742089, SDLK_CALCULATOR = 1073742090, SDLK_COMPUTER = 1073742091, SDLK_AC_SEARCH = 1073742092, SDLK_AC_HOME = 1073742093, SDLK_AC_BACK = 1073742094, SDLK_AC_FORWARD = 1073742095, SDLK_AC_STOP = 1073742096, SDLK_AC_REFRESH = 1073742097, SDLK_AC_BOOKMARKS = 1073742098, SDLK_BRIGHTNESSDOWN = 1073742099, SDLK_BRIGHTNESSUP = 1073742100, SDLK_DISPLAYSWITCH = 1073742101, SDLK_KBDILLUMTOGGLE = 1073742102, SDLK_KBDILLUMDOWN = 1073742103, SDLK_KBDILLUMUP = 1073742104, SDLK_EJECT = 1073742105, SDLK_SLEEP = 1073742106, SDLK_APP1 = 1073742107, SDLK_APP2 = 1073742108, SDLK_AUDIOREWIND = 1073742109, SDLK_AUDIOFASTFORWARD = 1073742110, _, }; pub const SDL_KeyCode = enum_unnamed_34; pub const KMOD_NONE = @enumToInt(enum_unnamed_35.KMOD_NONE); pub const KMOD_LSHIFT = @enumToInt(enum_unnamed_35.KMOD_LSHIFT); pub const KMOD_RSHIFT = @enumToInt(enum_unnamed_35.KMOD_RSHIFT); pub const KMOD_LCTRL = @enumToInt(enum_unnamed_35.KMOD_LCTRL); pub const KMOD_RCTRL = @enumToInt(enum_unnamed_35.KMOD_RCTRL); pub const KMOD_LALT = @enumToInt(enum_unnamed_35.KMOD_LALT); pub const KMOD_RALT = @enumToInt(enum_unnamed_35.KMOD_RALT); pub const KMOD_LGUI = @enumToInt(enum_unnamed_35.KMOD_LGUI); pub const KMOD_RGUI = @enumToInt(enum_unnamed_35.KMOD_RGUI); pub const KMOD_NUM = @enumToInt(enum_unnamed_35.KMOD_NUM); pub const KMOD_CAPS = @enumToInt(enum_unnamed_35.KMOD_CAPS); pub const KMOD_MODE = @enumToInt(enum_unnamed_35.KMOD_MODE); pub const KMOD_RESERVED = @enumToInt(enum_unnamed_35.KMOD_RESERVED); pub const KMOD_CTRL = @enumToInt(enum_unnamed_35.KMOD_CTRL); pub const KMOD_SHIFT = @enumToInt(enum_unnamed_35.KMOD_SHIFT); pub const KMOD_ALT = @enumToInt(enum_unnamed_35.KMOD_ALT); pub const KMOD_GUI = @enumToInt(enum_unnamed_35.KMOD_GUI); const enum_unnamed_35 = extern enum(c_int) { KMOD_NONE = 0, KMOD_LSHIFT = 1, KMOD_RSHIFT = 2, KMOD_LCTRL = 64, KMOD_RCTRL = 128, KMOD_LALT = 256, KMOD_RALT = 512, KMOD_LGUI = 1024, KMOD_RGUI = 2048, KMOD_NUM = 4096, KMOD_CAPS = 8192, KMOD_MODE = 16384, KMOD_RESERVED = 32768, KMOD_CTRL = 192, KMOD_SHIFT = 3, KMOD_ALT = 768, KMOD_GUI = 3072, _, }; pub const SDL_Keymod = enum_unnamed_35; pub const struct_SDL_Keysym = extern struct { scancode: SDL_Scancode, sym: SDL_Keycode, mod: u16, unused: u32, }; pub const SDL_Keysym = struct_SDL_Keysym; pub extern fn SDL_GetKeyboardFocus() ?*SDL_Window; pub extern fn SDL_GetKeyboardState(numkeys: [*c]c_int) [*c]const u8; pub extern fn SDL_GetModState() SDL_Keymod; pub extern fn SDL_SetModState(modstate: SDL_Keymod) void; pub extern fn SDL_GetKeyFromScancode(scancode: SDL_Scancode) SDL_Keycode; pub extern fn SDL_GetScancodeFromKey(key: SDL_Keycode) SDL_Scancode; pub extern fn SDL_GetScancodeName(scancode: SDL_Scancode) [*c]const u8; pub extern fn SDL_GetScancodeFromName(name: [*c]const u8) SDL_Scancode; pub extern fn SDL_GetKeyName(key: SDL_Keycode) [*c]const u8; pub extern fn SDL_GetKeyFromName(name: [*c]const u8) SDL_Keycode; pub extern fn SDL_StartTextInput() void; pub extern fn SDL_IsTextInputActive() SDL_bool; pub extern fn SDL_StopTextInput() void; pub extern fn SDL_SetTextInputRect(rect: [*c]SDL_Rect) void; pub extern fn SDL_HasScreenKeyboardSupport() SDL_bool; pub extern fn SDL_IsScreenKeyboardShown(window: ?*SDL_Window) SDL_bool; pub const struct_SDL_Cursor = opaque {}; pub const SDL_Cursor = struct_SDL_Cursor; pub const SDL_SYSTEM_CURSOR_ARROW = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_ARROW); pub const SDL_SYSTEM_CURSOR_IBEAM = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_IBEAM); pub const SDL_SYSTEM_CURSOR_WAIT = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_WAIT); pub const SDL_SYSTEM_CURSOR_CROSSHAIR = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_CROSSHAIR); pub const SDL_SYSTEM_CURSOR_WAITARROW = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_WAITARROW); pub const SDL_SYSTEM_CURSOR_SIZENWSE = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_SIZENWSE); pub const SDL_SYSTEM_CURSOR_SIZENESW = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_SIZENESW); pub const SDL_SYSTEM_CURSOR_SIZEWE = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_SIZEWE); pub const SDL_SYSTEM_CURSOR_SIZENS = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_SIZENS); pub const SDL_SYSTEM_CURSOR_SIZEALL = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_SIZEALL); pub const SDL_SYSTEM_CURSOR_NO = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_NO); pub const SDL_SYSTEM_CURSOR_HAND = @enumToInt(enum_unnamed_36.SDL_SYSTEM_CURSOR_HAND); pub const SDL_NUM_SYSTEM_CURSORS = @enumToInt(enum_unnamed_36.SDL_NUM_SYSTEM_CURSORS); const enum_unnamed_36 = extern enum(c_int) { SDL_SYSTEM_CURSOR_ARROW, SDL_SYSTEM_CURSOR_IBEAM, SDL_SYSTEM_CURSOR_WAIT, SDL_SYSTEM_CURSOR_CROSSHAIR, SDL_SYSTEM_CURSOR_WAITARROW, SDL_SYSTEM_CURSOR_SIZENWSE, SDL_SYSTEM_CURSOR_SIZENESW, SDL_SYSTEM_CURSOR_SIZEWE, SDL_SYSTEM_CURSOR_SIZENS, SDL_SYSTEM_CURSOR_SIZEALL, SDL_SYSTEM_CURSOR_NO, SDL_SYSTEM_CURSOR_HAND, SDL_NUM_SYSTEM_CURSORS, _, }; pub const SDL_SystemCursor = enum_unnamed_36; pub const SDL_MOUSEWHEEL_NORMAL = @enumToInt(enum_unnamed_37.SDL_MOUSEWHEEL_NORMAL); pub const SDL_MOUSEWHEEL_FLIPPED = @enumToInt(enum_unnamed_37.SDL_MOUSEWHEEL_FLIPPED); const enum_unnamed_37 = extern enum(c_int) { SDL_MOUSEWHEEL_NORMAL, SDL_MOUSEWHEEL_FLIPPED, _, }; pub const SDL_MouseWheelDirection = enum_unnamed_37; pub extern fn SDL_GetMouseFocus() ?*SDL_Window; pub extern fn SDL_GetMouseState(x: [*c]c_int, y: [*c]c_int) u32; pub extern fn SDL_GetGlobalMouseState(x: [*c]c_int, y: [*c]c_int) u32; pub extern fn SDL_GetRelativeMouseState(x: [*c]c_int, y: [*c]c_int) u32; pub extern fn SDL_WarpMouseInWindow(window: ?*SDL_Window, x: c_int, y: c_int) void; pub extern fn SDL_WarpMouseGlobal(x: c_int, y: c_int) c_int; pub extern fn SDL_SetRelativeMouseMode(enabled: SDL_bool) c_int; pub extern fn SDL_CaptureMouse(enabled: SDL_bool) c_int; pub extern fn SDL_GetRelativeMouseMode() SDL_bool; pub extern fn SDL_CreateCursor(data: [*c]const u8, mask: [*c]const u8, w: c_int, h: c_int, hot_x: c_int, hot_y: c_int) ?*SDL_Cursor; pub extern fn SDL_CreateColorCursor(surface: [*c]SDL_Surface, hot_x: c_int, hot_y: c_int) ?*SDL_Cursor; pub extern fn SDL_CreateSystemCursor(id: SDL_SystemCursor) ?*SDL_Cursor; pub extern fn SDL_SetCursor(cursor: ?*SDL_Cursor) void; pub extern fn SDL_GetCursor() ?*SDL_Cursor; pub extern fn SDL_GetDefaultCursor() ?*SDL_Cursor; pub extern fn SDL_FreeCursor(cursor: ?*SDL_Cursor) void; pub extern fn SDL_ShowCursor(toggle: c_int) c_int; pub const struct__SDL_Joystick = opaque {}; pub const SDL_Joystick = struct__SDL_Joystick; const struct_unnamed_38 = extern struct { data: [16]u8, }; pub const SDL_JoystickGUID = struct_unnamed_38; pub const SDL_JoystickID = i32; pub const SDL_JOYSTICK_TYPE_UNKNOWN = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_UNKNOWN); pub const SDL_JOYSTICK_TYPE_GAMECONTROLLER = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_GAMECONTROLLER); pub const SDL_JOYSTICK_TYPE_WHEEL = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_WHEEL); pub const SDL_JOYSTICK_TYPE_ARCADE_STICK = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_ARCADE_STICK); pub const SDL_JOYSTICK_TYPE_FLIGHT_STICK = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_FLIGHT_STICK); pub const SDL_JOYSTICK_TYPE_DANCE_PAD = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_DANCE_PAD); pub const SDL_JOYSTICK_TYPE_GUITAR = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_GUITAR); pub const SDL_JOYSTICK_TYPE_DRUM_KIT = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_DRUM_KIT); pub const SDL_JOYSTICK_TYPE_ARCADE_PAD = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_ARCADE_PAD); pub const SDL_JOYSTICK_TYPE_THROTTLE = @enumToInt(enum_unnamed_39.SDL_JOYSTICK_TYPE_THROTTLE); const enum_unnamed_39 = extern enum(c_int) { SDL_JOYSTICK_TYPE_UNKNOWN, SDL_JOYSTICK_TYPE_GAMECONTROLLER, SDL_JOYSTICK_TYPE_WHEEL, SDL_JOYSTICK_TYPE_ARCADE_STICK, SDL_JOYSTICK_TYPE_FLIGHT_STICK, SDL_JOYSTICK_TYPE_DANCE_PAD, SDL_JOYSTICK_TYPE_GUITAR, SDL_JOYSTICK_TYPE_DRUM_KIT, SDL_JOYSTICK_TYPE_ARCADE_PAD, SDL_JOYSTICK_TYPE_THROTTLE, _, }; pub const SDL_JoystickType = enum_unnamed_39; pub const SDL_JOYSTICK_POWER_UNKNOWN = @enumToInt(enum_unnamed_40.SDL_JOYSTICK_POWER_UNKNOWN); pub const SDL_JOYSTICK_POWER_EMPTY = @enumToInt(enum_unnamed_40.SDL_JOYSTICK_POWER_EMPTY); pub const SDL_JOYSTICK_POWER_LOW = @enumToInt(enum_unnamed_40.SDL_JOYSTICK_POWER_LOW); pub const SDL_JOYSTICK_POWER_MEDIUM = @enumToInt(enum_unnamed_40.SDL_JOYSTICK_POWER_MEDIUM); pub const SDL_JOYSTICK_POWER_FULL = @enumToInt(enum_unnamed_40.SDL_JOYSTICK_POWER_FULL); pub const SDL_JOYSTICK_POWER_WIRED = @enumToInt(enum_unnamed_40.SDL_JOYSTICK_POWER_WIRED); pub const SDL_JOYSTICK_POWER_MAX = @enumToInt(enum_unnamed_40.SDL_JOYSTICK_POWER_MAX); const enum_unnamed_40 = extern enum(c_int) { SDL_JOYSTICK_POWER_UNKNOWN = -1, SDL_JOYSTICK_POWER_EMPTY = 0, SDL_JOYSTICK_POWER_LOW = 1, SDL_JOYSTICK_POWER_MEDIUM = 2, SDL_JOYSTICK_POWER_FULL = 3, SDL_JOYSTICK_POWER_WIRED = 4, SDL_JOYSTICK_POWER_MAX = 5, _, }; pub const SDL_JoystickPowerLevel = enum_unnamed_40; pub extern fn SDL_LockJoysticks() void; pub extern fn SDL_UnlockJoysticks() void; pub extern fn SDL_NumJoysticks() c_int; pub extern fn SDL_JoystickNameForIndex(device_index: c_int) [*c]const u8; pub extern fn SDL_JoystickGetDevicePlayerIndex(device_index: c_int) c_int; pub extern fn SDL_JoystickGetDeviceGUID(device_index: c_int) SDL_JoystickGUID; pub extern fn SDL_JoystickGetDeviceVendor(device_index: c_int) u16; pub extern fn SDL_JoystickGetDeviceProduct(device_index: c_int) u16; pub extern fn SDL_JoystickGetDeviceProductVersion(device_index: c_int) u16; pub extern fn SDL_JoystickGetDeviceType(device_index: c_int) SDL_JoystickType; pub extern fn SDL_JoystickGetDeviceInstanceID(device_index: c_int) SDL_JoystickID; pub extern fn SDL_JoystickOpen(device_index: c_int) ?*SDL_Joystick; pub extern fn SDL_JoystickFromInstanceID(instance_id: SDL_JoystickID) ?*SDL_Joystick; pub extern fn SDL_JoystickFromPlayerIndex(player_index: c_int) ?*SDL_Joystick; pub extern fn SDL_JoystickAttachVirtual(type: SDL_JoystickType, naxes: c_int, nbuttons: c_int, nhats: c_int) c_int; pub extern fn SDL_JoystickDetachVirtual(device_index: c_int) c_int; pub extern fn SDL_JoystickIsVirtual(device_index: c_int) SDL_bool; pub extern fn SDL_JoystickSetVirtualAxis(joystick: ?*SDL_Joystick, axis: c_int, value: i16) c_int; pub extern fn SDL_JoystickSetVirtualButton(joystick: ?*SDL_Joystick, button: c_int, value: u8) c_int; pub extern fn SDL_JoystickSetVirtualHat(joystick: ?*SDL_Joystick, hat: c_int, value: u8) c_int; pub extern fn SDL_JoystickName(joystick: ?*SDL_Joystick) [*c]const u8; pub extern fn SDL_JoystickGetPlayerIndex(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickSetPlayerIndex(joystick: ?*SDL_Joystick, player_index: c_int) void; pub extern fn SDL_JoystickGetGUID(joystick: ?*SDL_Joystick) SDL_JoystickGUID; pub extern fn SDL_JoystickGetVendor(joystick: ?*SDL_Joystick) u16; pub extern fn SDL_JoystickGetProduct(joystick: ?*SDL_Joystick) u16; pub extern fn SDL_JoystickGetProductVersion(joystick: ?*SDL_Joystick) u16; pub extern fn SDL_JoystickGetSerial(joystick: ?*SDL_Joystick) [*c]const u8; pub extern fn SDL_JoystickGetType(joystick: ?*SDL_Joystick) SDL_JoystickType; pub extern fn SDL_JoystickGetGUIDString(guid: SDL_JoystickGUID, pszGUID: [*c]u8, cbGUID: c_int) void; pub extern fn SDL_JoystickGetGUIDFromString(pchGUID: [*c]const u8) SDL_JoystickGUID; pub extern fn SDL_JoystickGetAttached(joystick: ?*SDL_Joystick) SDL_bool; pub extern fn SDL_JoystickInstanceID(joystick: ?*SDL_Joystick) SDL_JoystickID; pub extern fn SDL_JoystickNumAxes(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumBalls(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumHats(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumButtons(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickUpdate() void; pub extern fn SDL_JoystickEventState(state: c_int) c_int; pub extern fn SDL_JoystickGetAxis(joystick: ?*SDL_Joystick, axis: c_int) i16; pub extern fn SDL_JoystickGetAxisInitialState(joystick: ?*SDL_Joystick, axis: c_int, state: [*c]i16) SDL_bool; pub extern fn SDL_JoystickGetHat(joystick: ?*SDL_Joystick, hat: c_int) u8; pub extern fn SDL_JoystickGetBall(joystick: ?*SDL_Joystick, ball: c_int, dx: [*c]c_int, dy: [*c]c_int) c_int; pub extern fn SDL_JoystickGetButton(joystick: ?*SDL_Joystick, button: c_int) u8; pub extern fn SDL_JoystickRumble(joystick: ?*SDL_Joystick, low_frequency_rumble: u16, high_frequency_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_JoystickRumbleTriggers(joystick: ?*SDL_Joystick, left_rumble: u16, right_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_JoystickHasLED(joystick: ?*SDL_Joystick) SDL_bool; pub extern fn SDL_JoystickSetLED(joystick: ?*SDL_Joystick, red: u8, green: u8, blue: u8) c_int; pub extern fn SDL_JoystickClose(joystick: ?*SDL_Joystick) void; pub extern fn SDL_JoystickCurrentPowerLevel(joystick: ?*SDL_Joystick) SDL_JoystickPowerLevel; pub const struct__SDL_Sensor = opaque {}; pub const SDL_Sensor = struct__SDL_Sensor; pub const SDL_SensorID = i32; pub const SDL_SENSOR_INVALID = @enumToInt(enum_unnamed_41.SDL_SENSOR_INVALID); pub const SDL_SENSOR_UNKNOWN = @enumToInt(enum_unnamed_41.SDL_SENSOR_UNKNOWN); pub const SDL_SENSOR_ACCEL = @enumToInt(enum_unnamed_41.SDL_SENSOR_ACCEL); pub const SDL_SENSOR_GYRO = @enumToInt(enum_unnamed_41.SDL_SENSOR_GYRO); const enum_unnamed_41 = extern enum(c_int) { SDL_SENSOR_INVALID = -1, SDL_SENSOR_UNKNOWN = 0, SDL_SENSOR_ACCEL = 1, SDL_SENSOR_GYRO = 2, _, }; pub const SDL_SensorType = enum_unnamed_41; pub extern fn SDL_LockSensors() void; pub extern fn SDL_UnlockSensors() void; pub extern fn SDL_NumSensors() c_int; pub extern fn SDL_SensorGetDeviceName(device_index: c_int) [*c]const u8; pub extern fn SDL_SensorGetDeviceType(device_index: c_int) SDL_SensorType; pub extern fn SDL_SensorGetDeviceNonPortableType(device_index: c_int) c_int; pub extern fn SDL_SensorGetDeviceInstanceID(device_index: c_int) SDL_SensorID; pub extern fn SDL_SensorOpen(device_index: c_int) ?*SDL_Sensor; pub extern fn SDL_SensorFromInstanceID(instance_id: SDL_SensorID) ?*SDL_Sensor; pub extern fn SDL_SensorGetName(sensor: ?*SDL_Sensor) [*c]const u8; pub extern fn SDL_SensorGetType(sensor: ?*SDL_Sensor) SDL_SensorType; pub extern fn SDL_SensorGetNonPortableType(sensor: ?*SDL_Sensor) c_int; pub extern fn SDL_SensorGetInstanceID(sensor: ?*SDL_Sensor) SDL_SensorID; pub extern fn SDL_SensorGetData(sensor: ?*SDL_Sensor, data: [*c]f32, num_values: c_int) c_int; pub extern fn SDL_SensorClose(sensor: ?*SDL_Sensor) void; pub extern fn SDL_SensorUpdate() void; pub const struct__SDL_GameController = opaque {}; pub const SDL_GameController = struct__SDL_GameController; pub const SDL_CONTROLLER_TYPE_UNKNOWN = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_UNKNOWN); pub const SDL_CONTROLLER_TYPE_XBOX360 = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_XBOX360); pub const SDL_CONTROLLER_TYPE_XBOXONE = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_XBOXONE); pub const SDL_CONTROLLER_TYPE_PS3 = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_PS3); pub const SDL_CONTROLLER_TYPE_PS4 = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_PS4); pub const SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO); pub const SDL_CONTROLLER_TYPE_VIRTUAL = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_VIRTUAL); pub const SDL_CONTROLLER_TYPE_PS5 = @enumToInt(enum_unnamed_42.SDL_CONTROLLER_TYPE_PS5); const enum_unnamed_42 = extern enum(c_int) { SDL_CONTROLLER_TYPE_UNKNOWN = 0, SDL_CONTROLLER_TYPE_XBOX360 = 1, SDL_CONTROLLER_TYPE_XBOXONE = 2, SDL_CONTROLLER_TYPE_PS3 = 3, SDL_CONTROLLER_TYPE_PS4 = 4, SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO = 5, SDL_CONTROLLER_TYPE_VIRTUAL = 6, SDL_CONTROLLER_TYPE_PS5 = 7, _, }; pub const SDL_GameControllerType = enum_unnamed_42; pub const SDL_CONTROLLER_BINDTYPE_NONE = @enumToInt(enum_unnamed_43.SDL_CONTROLLER_BINDTYPE_NONE); pub const SDL_CONTROLLER_BINDTYPE_BUTTON = @enumToInt(enum_unnamed_43.SDL_CONTROLLER_BINDTYPE_BUTTON); pub const SDL_CONTROLLER_BINDTYPE_AXIS = @enumToInt(enum_unnamed_43.SDL_CONTROLLER_BINDTYPE_AXIS); pub const SDL_CONTROLLER_BINDTYPE_HAT = @enumToInt(enum_unnamed_43.SDL_CONTROLLER_BINDTYPE_HAT); const enum_unnamed_43 = extern enum(c_int) { SDL_CONTROLLER_BINDTYPE_NONE = 0, SDL_CONTROLLER_BINDTYPE_BUTTON = 1, SDL_CONTROLLER_BINDTYPE_AXIS = 2, SDL_CONTROLLER_BINDTYPE_HAT = 3, _, }; pub const SDL_GameControllerBindType = enum_unnamed_43; const struct_unnamed_45 = extern struct { hat: c_int, hat_mask: c_int, }; const union_unnamed_44 = extern union { button: c_int, axis: c_int, hat: struct_unnamed_45, }; pub const struct_SDL_GameControllerButtonBind = extern struct { bindType: SDL_GameControllerBindType, value: union_unnamed_44, }; pub const SDL_GameControllerButtonBind = struct_SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerAddMappingsFromRW(rw: [*c]SDL_RWops, freerw: c_int) c_int; pub extern fn SDL_GameControllerAddMapping(mappingString: [*c]const u8) c_int; pub extern fn SDL_GameControllerNumMappings() c_int; pub extern fn SDL_GameControllerMappingForIndex(mapping_index: c_int) [*c]u8; pub extern fn SDL_GameControllerMappingForGUID(guid: SDL_JoystickGUID) [*c]u8; pub extern fn SDL_GameControllerMapping(gamecontroller: ?*SDL_GameController) [*c]u8; pub extern fn SDL_IsGameController(joystick_index: c_int) SDL_bool; pub extern fn SDL_GameControllerNameForIndex(joystick_index: c_int) [*c]const u8; pub extern fn SDL_GameControllerTypeForIndex(joystick_index: c_int) SDL_GameControllerType; pub extern fn SDL_GameControllerMappingForDeviceIndex(joystick_index: c_int) [*c]u8; pub extern fn SDL_GameControllerOpen(joystick_index: c_int) ?*SDL_GameController; pub extern fn SDL_GameControllerFromInstanceID(joyid: SDL_JoystickID) ?*SDL_GameController; pub extern fn SDL_GameControllerFromPlayerIndex(player_index: c_int) ?*SDL_GameController; pub extern fn SDL_GameControllerName(gamecontroller: ?*SDL_GameController) [*c]const u8; pub extern fn SDL_GameControllerGetType(gamecontroller: ?*SDL_GameController) SDL_GameControllerType; pub extern fn SDL_GameControllerGetPlayerIndex(gamecontroller: ?*SDL_GameController) c_int; pub extern fn SDL_GameControllerSetPlayerIndex(gamecontroller: ?*SDL_GameController, player_index: c_int) void; pub extern fn SDL_GameControllerGetVendor(gamecontroller: ?*SDL_GameController) u16; pub extern fn SDL_GameControllerGetProduct(gamecontroller: ?*SDL_GameController) u16; pub extern fn SDL_GameControllerGetProductVersion(gamecontroller: ?*SDL_GameController) u16; pub extern fn SDL_GameControllerGetSerial(gamecontroller: ?*SDL_GameController) [*c]const u8; pub extern fn SDL_GameControllerGetAttached(gamecontroller: ?*SDL_GameController) SDL_bool; pub extern fn SDL_GameControllerGetJoystick(gamecontroller: ?*SDL_GameController) ?*SDL_Joystick; pub extern fn SDL_GameControllerEventState(state: c_int) c_int; pub extern fn SDL_GameControllerUpdate() void; pub const SDL_CONTROLLER_AXIS_INVALID = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_INVALID); pub const SDL_CONTROLLER_AXIS_LEFTX = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_LEFTX); pub const SDL_CONTROLLER_AXIS_LEFTY = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_LEFTY); pub const SDL_CONTROLLER_AXIS_RIGHTX = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_RIGHTX); pub const SDL_CONTROLLER_AXIS_RIGHTY = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_RIGHTY); pub const SDL_CONTROLLER_AXIS_TRIGGERLEFT = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_TRIGGERLEFT); pub const SDL_CONTROLLER_AXIS_TRIGGERRIGHT = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_TRIGGERRIGHT); pub const SDL_CONTROLLER_AXIS_MAX = @enumToInt(enum_unnamed_46.SDL_CONTROLLER_AXIS_MAX); const enum_unnamed_46 = extern enum(c_int) { SDL_CONTROLLER_AXIS_INVALID = -1, SDL_CONTROLLER_AXIS_LEFTX = 0, SDL_CONTROLLER_AXIS_LEFTY = 1, SDL_CONTROLLER_AXIS_RIGHTX = 2, SDL_CONTROLLER_AXIS_RIGHTY = 3, SDL_CONTROLLER_AXIS_TRIGGERLEFT = 4, SDL_CONTROLLER_AXIS_TRIGGERRIGHT = 5, SDL_CONTROLLER_AXIS_MAX = 6, _, }; pub const SDL_GameControllerAxis = enum_unnamed_46; pub extern fn SDL_GameControllerGetAxisFromString(pchString: [*c]const u8) SDL_GameControllerAxis; pub extern fn SDL_GameControllerGetStringForAxis(axis: SDL_GameControllerAxis) [*c]const u8; pub extern fn SDL_GameControllerGetBindForAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerHasAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) SDL_bool; pub extern fn SDL_GameControllerGetAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) i16; pub const SDL_CONTROLLER_BUTTON_INVALID = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_INVALID); pub const SDL_CONTROLLER_BUTTON_A = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_A); pub const SDL_CONTROLLER_BUTTON_B = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_B); pub const SDL_CONTROLLER_BUTTON_X = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_X); pub const SDL_CONTROLLER_BUTTON_Y = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_Y); pub const SDL_CONTROLLER_BUTTON_BACK = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_BACK); pub const SDL_CONTROLLER_BUTTON_GUIDE = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_GUIDE); pub const SDL_CONTROLLER_BUTTON_START = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_START); pub const SDL_CONTROLLER_BUTTON_LEFTSTICK = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_LEFTSTICK); pub const SDL_CONTROLLER_BUTTON_RIGHTSTICK = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_RIGHTSTICK); pub const SDL_CONTROLLER_BUTTON_LEFTSHOULDER = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_LEFTSHOULDER); pub const SDL_CONTROLLER_BUTTON_RIGHTSHOULDER = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); pub const SDL_CONTROLLER_BUTTON_DPAD_UP = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_DPAD_UP); pub const SDL_CONTROLLER_BUTTON_DPAD_DOWN = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_DPAD_DOWN); pub const SDL_CONTROLLER_BUTTON_DPAD_LEFT = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_DPAD_LEFT); pub const SDL_CONTROLLER_BUTTON_DPAD_RIGHT = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_DPAD_RIGHT); pub const SDL_CONTROLLER_BUTTON_MISC1 = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_MISC1); pub const SDL_CONTROLLER_BUTTON_PADDLE1 = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_PADDLE1); pub const SDL_CONTROLLER_BUTTON_PADDLE2 = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_PADDLE2); pub const SDL_CONTROLLER_BUTTON_PADDLE3 = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_PADDLE3); pub const SDL_CONTROLLER_BUTTON_PADDLE4 = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_PADDLE4); pub const SDL_CONTROLLER_BUTTON_TOUCHPAD = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_TOUCHPAD); pub const SDL_CONTROLLER_BUTTON_MAX = @enumToInt(enum_unnamed_47.SDL_CONTROLLER_BUTTON_MAX); const enum_unnamed_47 = extern enum(c_int) { SDL_CONTROLLER_BUTTON_INVALID = -1, SDL_CONTROLLER_BUTTON_A = 0, SDL_CONTROLLER_BUTTON_B = 1, SDL_CONTROLLER_BUTTON_X = 2, SDL_CONTROLLER_BUTTON_Y = 3, SDL_CONTROLLER_BUTTON_BACK = 4, SDL_CONTROLLER_BUTTON_GUIDE = 5, SDL_CONTROLLER_BUTTON_START = 6, SDL_CONTROLLER_BUTTON_LEFTSTICK = 7, SDL_CONTROLLER_BUTTON_RIGHTSTICK = 8, SDL_CONTROLLER_BUTTON_LEFTSHOULDER = 9, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER = 10, SDL_CONTROLLER_BUTTON_DPAD_UP = 11, SDL_CONTROLLER_BUTTON_DPAD_DOWN = 12, SDL_CONTROLLER_BUTTON_DPAD_LEFT = 13, SDL_CONTROLLER_BUTTON_DPAD_RIGHT = 14, SDL_CONTROLLER_BUTTON_MISC1 = 15, SDL_CONTROLLER_BUTTON_PADDLE1 = 16, SDL_CONTROLLER_BUTTON_PADDLE2 = 17, SDL_CONTROLLER_BUTTON_PADDLE3 = 18, SDL_CONTROLLER_BUTTON_PADDLE4 = 19, SDL_CONTROLLER_BUTTON_TOUCHPAD = 20, SDL_CONTROLLER_BUTTON_MAX = 21, _, }; pub const SDL_GameControllerButton = enum_unnamed_47; pub extern fn SDL_GameControllerGetButtonFromString(pchString: [*c]const u8) SDL_GameControllerButton; pub extern fn SDL_GameControllerGetStringForButton(button: SDL_GameControllerButton) [*c]const u8; pub extern fn SDL_GameControllerGetBindForButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerHasButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) SDL_bool; pub extern fn SDL_GameControllerGetButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) u8; pub extern fn SDL_GameControllerGetNumTouchpads(gamecontroller: ?*SDL_GameController) c_int; pub extern fn SDL_GameControllerGetNumTouchpadFingers(gamecontroller: ?*SDL_GameController, touchpad: c_int) c_int; pub extern fn SDL_GameControllerGetTouchpadFinger(gamecontroller: ?*SDL_GameController, touchpad: c_int, finger: c_int, state: [*c]u8, x: [*c]f32, y: [*c]f32, pressure: [*c]f32) c_int; pub extern fn SDL_GameControllerHasSensor(gamecontroller: ?*SDL_GameController, type: SDL_SensorType) SDL_bool; pub extern fn SDL_GameControllerSetSensorEnabled(gamecontroller: ?*SDL_GameController, type: SDL_SensorType, enabled: SDL_bool) c_int; pub extern fn SDL_GameControllerIsSensorEnabled(gamecontroller: ?*SDL_GameController, type: SDL_SensorType) SDL_bool; pub extern fn SDL_GameControllerGetSensorData(gamecontroller: ?*SDL_GameController, type: SDL_SensorType, data: [*c]f32, num_values: c_int) c_int; pub extern fn SDL_GameControllerRumble(gamecontroller: ?*SDL_GameController, low_frequency_rumble: u16, high_frequency_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_GameControllerRumbleTriggers(gamecontroller: ?*SDL_GameController, left_rumble: u16, right_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_GameControllerHasLED(gamecontroller: ?*SDL_GameController) SDL_bool; pub extern fn SDL_GameControllerSetLED(gamecontroller: ?*SDL_GameController, red: u8, green: u8, blue: u8) c_int; pub extern fn SDL_GameControllerClose(gamecontroller: ?*SDL_GameController) void; pub const SDL_TouchID = i64; pub const SDL_FingerID = i64; pub const SDL_TOUCH_DEVICE_INVALID = @enumToInt(enum_unnamed_48.SDL_TOUCH_DEVICE_INVALID); pub const SDL_TOUCH_DEVICE_DIRECT = @enumToInt(enum_unnamed_48.SDL_TOUCH_DEVICE_DIRECT); pub const SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE = @enumToInt(enum_unnamed_48.SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE); pub const SDL_TOUCH_DEVICE_INDIRECT_RELATIVE = @enumToInt(enum_unnamed_48.SDL_TOUCH_DEVICE_INDIRECT_RELATIVE); const enum_unnamed_48 = extern enum(c_int) { SDL_TOUCH_DEVICE_INVALID = -1, SDL_TOUCH_DEVICE_DIRECT = 0, SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE = 1, SDL_TOUCH_DEVICE_INDIRECT_RELATIVE = 2, _, }; pub const SDL_TouchDeviceType = enum_unnamed_48; pub const struct_SDL_Finger = extern struct { id: SDL_FingerID, x: f32, y: f32, pressure: f32, }; pub const SDL_Finger = struct_SDL_Finger; pub extern fn SDL_GetNumTouchDevices() c_int; pub extern fn SDL_GetTouchDevice(index: c_int) SDL_TouchID; pub extern fn SDL_GetTouchDeviceType(touchID: SDL_TouchID) SDL_TouchDeviceType; pub extern fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) c_int; pub extern fn SDL_GetTouchFinger(touchID: SDL_TouchID, index: c_int) [*c]SDL_Finger; pub const SDL_GestureID = i64; pub extern fn SDL_RecordGesture(touchId: SDL_TouchID) c_int; pub extern fn SDL_SaveAllDollarTemplates(dst: [*c]SDL_RWops) c_int; pub extern fn SDL_SaveDollarTemplate(gestureId: SDL_GestureID, dst: [*c]SDL_RWops) c_int; pub extern fn SDL_LoadDollarTemplates(touchId: SDL_TouchID, src: [*c]SDL_RWops) c_int; pub const SDL_FIRSTEVENT = @enumToInt(enum_unnamed_49.SDL_FIRSTEVENT); pub const SDL_QUIT = @enumToInt(enum_unnamed_49.SDL_QUIT); pub const SDL_APP_TERMINATING = @enumToInt(enum_unnamed_49.SDL_APP_TERMINATING); pub const SDL_APP_LOWMEMORY = @enumToInt(enum_unnamed_49.SDL_APP_LOWMEMORY); pub const SDL_APP_WILLENTERBACKGROUND = @enumToInt(enum_unnamed_49.SDL_APP_WILLENTERBACKGROUND); pub const SDL_APP_DIDENTERBACKGROUND = @enumToInt(enum_unnamed_49.SDL_APP_DIDENTERBACKGROUND); pub const SDL_APP_WILLENTERFOREGROUND = @enumToInt(enum_unnamed_49.SDL_APP_WILLENTERFOREGROUND); pub const SDL_APP_DIDENTERFOREGROUND = @enumToInt(enum_unnamed_49.SDL_APP_DIDENTERFOREGROUND); pub const SDL_LOCALECHANGED = @enumToInt(enum_unnamed_49.SDL_LOCALECHANGED); pub const SDL_DISPLAYEVENT = @enumToInt(enum_unnamed_49.SDL_DISPLAYEVENT); pub const SDL_WINDOWEVENT = @enumToInt(enum_unnamed_49.SDL_WINDOWEVENT); pub const SDL_SYSWMEVENT = @enumToInt(enum_unnamed_49.SDL_SYSWMEVENT); pub const SDL_KEYDOWN = @enumToInt(enum_unnamed_49.SDL_KEYDOWN); pub const SDL_KEYUP = @enumToInt(enum_unnamed_49.SDL_KEYUP); pub const SDL_TEXTEDITING = @enumToInt(enum_unnamed_49.SDL_TEXTEDITING); pub const SDL_TEXTINPUT = @enumToInt(enum_unnamed_49.SDL_TEXTINPUT); pub const SDL_KEYMAPCHANGED = @enumToInt(enum_unnamed_49.SDL_KEYMAPCHANGED); pub const SDL_MOUSEMOTION = @enumToInt(enum_unnamed_49.SDL_MOUSEMOTION); pub const SDL_MOUSEBUTTONDOWN = @enumToInt(enum_unnamed_49.SDL_MOUSEBUTTONDOWN); pub const SDL_MOUSEBUTTONUP = @enumToInt(enum_unnamed_49.SDL_MOUSEBUTTONUP); pub const SDL_MOUSEWHEEL = @enumToInt(enum_unnamed_49.SDL_MOUSEWHEEL); pub const SDL_JOYAXISMOTION = @enumToInt(enum_unnamed_49.SDL_JOYAXISMOTION); pub const SDL_JOYBALLMOTION = @enumToInt(enum_unnamed_49.SDL_JOYBALLMOTION); pub const SDL_JOYHATMOTION = @enumToInt(enum_unnamed_49.SDL_JOYHATMOTION); pub const SDL_JOYBUTTONDOWN = @enumToInt(enum_unnamed_49.SDL_JOYBUTTONDOWN); pub const SDL_JOYBUTTONUP = @enumToInt(enum_unnamed_49.SDL_JOYBUTTONUP); pub const SDL_JOYDEVICEADDED = @enumToInt(enum_unnamed_49.SDL_JOYDEVICEADDED); pub const SDL_JOYDEVICEREMOVED = @enumToInt(enum_unnamed_49.SDL_JOYDEVICEREMOVED); pub const SDL_CONTROLLERAXISMOTION = @enumToInt(enum_unnamed_49.SDL_CONTROLLERAXISMOTION); pub const SDL_CONTROLLERBUTTONDOWN = @enumToInt(enum_unnamed_49.SDL_CONTROLLERBUTTONDOWN); pub const SDL_CONTROLLERBUTTONUP = @enumToInt(enum_unnamed_49.SDL_CONTROLLERBUTTONUP); pub const SDL_CONTROLLERDEVICEADDED = @enumToInt(enum_unnamed_49.SDL_CONTROLLERDEVICEADDED); pub const SDL_CONTROLLERDEVICEREMOVED = @enumToInt(enum_unnamed_49.SDL_CONTROLLERDEVICEREMOVED); pub const SDL_CONTROLLERDEVICEREMAPPED = @enumToInt(enum_unnamed_49.SDL_CONTROLLERDEVICEREMAPPED); pub const SDL_CONTROLLERTOUCHPADDOWN = @enumToInt(enum_unnamed_49.SDL_CONTROLLERTOUCHPADDOWN); pub const SDL_CONTROLLERTOUCHPADMOTION = @enumToInt(enum_unnamed_49.SDL_CONTROLLERTOUCHPADMOTION); pub const SDL_CONTROLLERTOUCHPADUP = @enumToInt(enum_unnamed_49.SDL_CONTROLLERTOUCHPADUP); pub const SDL_CONTROLLERSENSORUPDATE = @enumToInt(enum_unnamed_49.SDL_CONTROLLERSENSORUPDATE); pub const SDL_FINGERDOWN = @enumToInt(enum_unnamed_49.SDL_FINGERDOWN); pub const SDL_FINGERUP = @enumToInt(enum_unnamed_49.SDL_FINGERUP); pub const SDL_FINGERMOTION = @enumToInt(enum_unnamed_49.SDL_FINGERMOTION); pub const SDL_DOLLARGESTURE = @enumToInt(enum_unnamed_49.SDL_DOLLARGESTURE); pub const SDL_DOLLARRECORD = @enumToInt(enum_unnamed_49.SDL_DOLLARRECORD); pub const SDL_MULTIGESTURE = @enumToInt(enum_unnamed_49.SDL_MULTIGESTURE); pub const SDL_CLIPBOARDUPDATE = @enumToInt(enum_unnamed_49.SDL_CLIPBOARDUPDATE); pub const SDL_DROPFILE = @enumToInt(enum_unnamed_49.SDL_DROPFILE); pub const SDL_DROPTEXT = @enumToInt(enum_unnamed_49.SDL_DROPTEXT); pub const SDL_DROPBEGIN = @enumToInt(enum_unnamed_49.SDL_DROPBEGIN); pub const SDL_DROPCOMPLETE = @enumToInt(enum_unnamed_49.SDL_DROPCOMPLETE); pub const SDL_AUDIODEVICEADDED = @enumToInt(enum_unnamed_49.SDL_AUDIODEVICEADDED); pub const SDL_AUDIODEVICEREMOVED = @enumToInt(enum_unnamed_49.SDL_AUDIODEVICEREMOVED); pub const SDL_SENSORUPDATE = @enumToInt(enum_unnamed_49.SDL_SENSORUPDATE); pub const SDL_RENDER_TARGETS_RESET = @enumToInt(enum_unnamed_49.SDL_RENDER_TARGETS_RESET); pub const SDL_RENDER_DEVICE_RESET = @enumToInt(enum_unnamed_49.SDL_RENDER_DEVICE_RESET); pub const SDL_USEREVENT = @enumToInt(enum_unnamed_49.SDL_USEREVENT); pub const SDL_LASTEVENT = @enumToInt(enum_unnamed_49.SDL_LASTEVENT); const enum_unnamed_49 = extern enum(c_int) { SDL_FIRSTEVENT = 0, SDL_QUIT = 256, SDL_APP_TERMINATING = 257, SDL_APP_LOWMEMORY = 258, SDL_APP_WILLENTERBACKGROUND = 259, SDL_APP_DIDENTERBACKGROUND = 260, SDL_APP_WILLENTERFOREGROUND = 261, SDL_APP_DIDENTERFOREGROUND = 262, SDL_LOCALECHANGED = 263, SDL_DISPLAYEVENT = 336, SDL_WINDOWEVENT = 512, SDL_SYSWMEVENT = 513, SDL_KEYDOWN = 768, SDL_KEYUP = 769, SDL_TEXTEDITING = 770, SDL_TEXTINPUT = 771, SDL_KEYMAPCHANGED = 772, SDL_MOUSEMOTION = 1024, SDL_MOUSEBUTTONDOWN = 1025, SDL_MOUSEBUTTONUP = 1026, SDL_MOUSEWHEEL = 1027, SDL_JOYAXISMOTION = 1536, SDL_JOYBALLMOTION = 1537, SDL_JOYHATMOTION = 1538, SDL_JOYBUTTONDOWN = 1539, SDL_JOYBUTTONUP = 1540, SDL_JOYDEVICEADDED = 1541, SDL_JOYDEVICEREMOVED = 1542, SDL_CONTROLLERAXISMOTION = 1616, SDL_CONTROLLERBUTTONDOWN = 1617, SDL_CONTROLLERBUTTONUP = 1618, SDL_CONTROLLERDEVICEADDED = 1619, SDL_CONTROLLERDEVICEREMOVED = 1620, SDL_CONTROLLERDEVICEREMAPPED = 1621, SDL_CONTROLLERTOUCHPADDOWN = 1622, SDL_CONTROLLERTOUCHPADMOTION = 1623, SDL_CONTROLLERTOUCHPADUP = 1624, SDL_CONTROLLERSENSORUPDATE = 1625, SDL_FINGERDOWN = 1792, SDL_FINGERUP = 1793, SDL_FINGERMOTION = 1794, SDL_DOLLARGESTURE = 2048, SDL_DOLLARRECORD = 2049, SDL_MULTIGESTURE = 2050, SDL_CLIPBOARDUPDATE = 2304, SDL_DROPFILE = 4096, SDL_DROPTEXT = 4097, SDL_DROPBEGIN = 4098, SDL_DROPCOMPLETE = 4099, SDL_AUDIODEVICEADDED = 4352, SDL_AUDIODEVICEREMOVED = 4353, SDL_SENSORUPDATE = 4608, SDL_RENDER_TARGETS_RESET = 8192, SDL_RENDER_DEVICE_RESET = 8193, SDL_USEREVENT = 32768, SDL_LASTEVENT = 65535, _, }; pub const SDL_EventType = enum_unnamed_49; pub const struct_SDL_CommonEvent = extern struct { type: u32, timestamp: u32, }; pub const SDL_CommonEvent = struct_SDL_CommonEvent; pub const struct_SDL_DisplayEvent = extern struct { type: u32, timestamp: u32, display: u32, event: u8, padding1: u8, padding2: u8, padding3: u8, data1: i32, }; pub const SDL_DisplayEvent = struct_SDL_DisplayEvent; pub const struct_SDL_WindowEvent = extern struct { type: u32, timestamp: u32, windowID: u32, event: u8, padding1: u8, padding2: u8, padding3: u8, data1: i32, data2: i32, }; pub const SDL_WindowEvent = struct_SDL_WindowEvent; pub const struct_SDL_KeyboardEvent = extern struct { type: u32, timestamp: u32, windowID: u32, state: u8, repeat: u8, padding2: u8, padding3: u8, keysym: SDL_Keysym, }; pub const SDL_KeyboardEvent = struct_SDL_KeyboardEvent; pub const struct_SDL_TextEditingEvent = extern struct { type: u32, timestamp: u32, windowID: u32, text: [32]u8, start: i32, length: i32, }; pub const SDL_TextEditingEvent = struct_SDL_TextEditingEvent; pub const struct_SDL_TextInputEvent = extern struct { type: u32, timestamp: u32, windowID: u32, text: [32]u8, }; pub const SDL_TextInputEvent = struct_SDL_TextInputEvent; pub const struct_SDL_MouseMotionEvent = extern struct { type: u32, timestamp: u32, windowID: u32, which: u32, state: u32, x: i32, y: i32, xrel: i32, yrel: i32, }; pub const SDL_MouseMotionEvent = struct_SDL_MouseMotionEvent; pub const struct_SDL_MouseButtonEvent = extern struct { type: u32, timestamp: u32, windowID: u32, which: u32, button: u8, state: u8, clicks: u8, padding1: u8, x: i32, y: i32, }; pub const SDL_MouseButtonEvent = struct_SDL_MouseButtonEvent; pub const struct_SDL_MouseWheelEvent = extern struct { type: u32, timestamp: u32, windowID: u32, which: u32, x: i32, y: i32, direction: u32, }; pub const SDL_MouseWheelEvent = struct_SDL_MouseWheelEvent; pub const struct_SDL_JoyAxisEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, axis: u8, padding1: u8, padding2: u8, padding3: u8, value: i16, padding4: u16, }; pub const SDL_JoyAxisEvent = struct_SDL_JoyAxisEvent; pub const struct_SDL_JoyBallEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, ball: u8, padding1: u8, padding2: u8, padding3: u8, xrel: i16, yrel: i16, }; pub const SDL_JoyBallEvent = struct_SDL_JoyBallEvent; pub const struct_SDL_JoyHatEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, hat: u8, value: u8, padding1: u8, padding2: u8, }; pub const SDL_JoyHatEvent = struct_SDL_JoyHatEvent; pub const struct_SDL_JoyButtonEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, button: u8, state: u8, padding1: u8, padding2: u8, }; pub const SDL_JoyButtonEvent = struct_SDL_JoyButtonEvent; pub const struct_SDL_JoyDeviceEvent = extern struct { type: u32, timestamp: u32, which: i32, }; pub const SDL_JoyDeviceEvent = struct_SDL_JoyDeviceEvent; pub const struct_SDL_ControllerAxisEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, axis: u8, padding1: u8, padding2: u8, padding3: u8, value: i16, padding4: u16, }; pub const SDL_ControllerAxisEvent = struct_SDL_ControllerAxisEvent; pub const struct_SDL_ControllerButtonEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, button: u8, state: u8, padding1: u8, padding2: u8, }; pub const SDL_ControllerButtonEvent = struct_SDL_ControllerButtonEvent; pub const struct_SDL_ControllerDeviceEvent = extern struct { type: u32, timestamp: u32, which: i32, }; pub const SDL_ControllerDeviceEvent = struct_SDL_ControllerDeviceEvent; pub const struct_SDL_ControllerTouchpadEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, touchpad: i32, finger: i32, x: f32, y: f32, pressure: f32, }; pub const SDL_ControllerTouchpadEvent = struct_SDL_ControllerTouchpadEvent; pub const struct_SDL_ControllerSensorEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, sensor: i32, data: [3]f32, }; pub const SDL_ControllerSensorEvent = struct_SDL_ControllerSensorEvent; pub const struct_SDL_AudioDeviceEvent = extern struct { type: u32, timestamp: u32, which: u32, iscapture: u8, padding1: u8, padding2: u8, padding3: u8, }; pub const SDL_AudioDeviceEvent = struct_SDL_AudioDeviceEvent; pub const struct_SDL_TouchFingerEvent = extern struct { type: u32, timestamp: u32, touchId: SDL_TouchID, fingerId: SDL_FingerID, x: f32, y: f32, dx: f32, dy: f32, pressure: f32, windowID: u32, }; pub const SDL_TouchFingerEvent = struct_SDL_TouchFingerEvent; pub const struct_SDL_MultiGestureEvent = extern struct { type: u32, timestamp: u32, touchId: SDL_TouchID, dTheta: f32, dDist: f32, x: f32, y: f32, numFingers: u16, padding: u16, }; pub const SDL_MultiGestureEvent = struct_SDL_MultiGestureEvent; pub const struct_SDL_DollarGestureEvent = extern struct { type: u32, timestamp: u32, touchId: SDL_TouchID, gestureId: SDL_GestureID, numFingers: u32, @"error": f32, x: f32, y: f32, }; pub const SDL_DollarGestureEvent = struct_SDL_DollarGestureEvent; pub const struct_SDL_DropEvent = extern struct { type: u32, timestamp: u32, file: [*c]u8, windowID: u32, }; pub const SDL_DropEvent = struct_SDL_DropEvent; pub const struct_SDL_SensorEvent = extern struct { type: u32, timestamp: u32, which: i32, data: [6]f32, }; pub const SDL_SensorEvent = struct_SDL_SensorEvent; pub const struct_SDL_QuitEvent = extern struct { type: u32, timestamp: u32, }; pub const SDL_QuitEvent = struct_SDL_QuitEvent; pub const struct_SDL_OSEvent = extern struct { type: u32, timestamp: u32, }; pub const SDL_OSEvent = struct_SDL_OSEvent; pub const struct_SDL_UserEvent = extern struct { type: u32, timestamp: u32, windowID: u32, code: i32, data1: ?*c_void, data2: ?*c_void, }; pub const SDL_UserEvent = struct_SDL_UserEvent; pub const struct_SDL_SysWMmsg = opaque {}; pub const SDL_SysWMmsg = struct_SDL_SysWMmsg; pub const struct_SDL_SysWMEvent = extern struct { type: u32, timestamp: u32, msg: ?*SDL_SysWMmsg, }; pub const SDL_SysWMEvent = struct_SDL_SysWMEvent; pub const union_SDL_Event = extern union { type: u32, common: SDL_CommonEvent, display: SDL_DisplayEvent, window: SDL_WindowEvent, key: SDL_KeyboardEvent, edit: SDL_TextEditingEvent, text: SDL_TextInputEvent, motion: SDL_MouseMotionEvent, button: SDL_MouseButtonEvent, wheel: SDL_MouseWheelEvent, jaxis: SDL_JoyAxisEvent, jball: SDL_JoyBallEvent, jhat: SDL_JoyHatEvent, jbutton: SDL_JoyButtonEvent, jdevice: SDL_JoyDeviceEvent, caxis: SDL_ControllerAxisEvent, cbutton: SDL_ControllerButtonEvent, cdevice: SDL_ControllerDeviceEvent, ctouchpad: SDL_ControllerTouchpadEvent, csensor: SDL_ControllerSensorEvent, adevice: SDL_AudioDeviceEvent, sensor: SDL_SensorEvent, quit: SDL_QuitEvent, user: SDL_UserEvent, syswm: SDL_SysWMEvent, tfinger: SDL_TouchFingerEvent, mgesture: SDL_MultiGestureEvent, dgesture: SDL_DollarGestureEvent, drop: SDL_DropEvent, padding: [56]u8, }; pub const SDL_Event = union_SDL_Event; pub extern fn SDL_PumpEvents() void; pub const SDL_ADDEVENT = @enumToInt(enum_unnamed_50.SDL_ADDEVENT); pub const SDL_PEEKEVENT = @enumToInt(enum_unnamed_50.SDL_PEEKEVENT); pub const SDL_GETEVENT = @enumToInt(enum_unnamed_50.SDL_GETEVENT); const enum_unnamed_50 = extern enum(c_int) { SDL_ADDEVENT, SDL_PEEKEVENT, SDL_GETEVENT, _, }; pub const SDL_eventaction = enum_unnamed_50; pub extern fn SDL_PeepEvents(events: [*c]SDL_Event, numevents: c_int, action: SDL_eventaction, minType: u32, maxType: u32) c_int; pub extern fn SDL_HasEvent(type: u32) SDL_bool; pub extern fn SDL_HasEvents(minType: u32, maxType: u32) SDL_bool; pub extern fn SDL_FlushEvent(type: u32) void; pub extern fn SDL_FlushEvents(minType: u32, maxType: u32) void; pub extern fn SDL_PollEvent(event: [*c]SDL_Event) c_int; pub extern fn SDL_WaitEvent(event: [*c]SDL_Event) c_int; pub extern fn SDL_WaitEventTimeout(event: [*c]SDL_Event, timeout: c_int) c_int; pub extern fn SDL_PushEvent(event: [*c]SDL_Event) c_int; pub const SDL_EventFilter = ?fn (?*c_void, [*c]SDL_Event) callconv(.C) c_int; pub extern fn SDL_SetEventFilter(filter: SDL_EventFilter, userdata: ?*c_void) void; pub extern fn SDL_GetEventFilter(filter: [*c]SDL_EventFilter, userdata: [*c]?*c_void) SDL_bool; pub extern fn SDL_AddEventWatch(filter: SDL_EventFilter, userdata: ?*c_void) void; pub extern fn SDL_DelEventWatch(filter: SDL_EventFilter, userdata: ?*c_void) void; pub extern fn SDL_FilterEvents(filter: SDL_EventFilter, userdata: ?*c_void) void; pub extern fn SDL_EventState(type: u32, state: c_int) u8; pub extern fn SDL_RegisterEvents(numevents: c_int) u32; pub extern fn SDL_GetBasePath() [*c]u8; pub extern fn SDL_GetPrefPath(org: [*c]const u8, app: [*c]const u8) [*c]u8; pub const struct__SDL_Haptic = opaque {}; pub const SDL_Haptic = struct__SDL_Haptic; pub const struct_SDL_HapticDirection = extern struct { type: u8, dir: [3]i32, }; pub const SDL_HapticDirection = struct_SDL_HapticDirection; pub const struct_SDL_HapticConstant = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, level: i16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const SDL_HapticConstant = struct_SDL_HapticConstant; pub const struct_SDL_HapticPeriodic = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, period: u16, magnitude: i16, offset: i16, phase: u16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const SDL_HapticPeriodic = struct_SDL_HapticPeriodic; pub const struct_SDL_HapticCondition = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, right_sat: [3]u16, left_sat: [3]u16, right_coeff: [3]i16, left_coeff: [3]i16, deadband: [3]u16, center: [3]i16, }; pub const SDL_HapticCondition = struct_SDL_HapticCondition; pub const struct_SDL_HapticRamp = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, start: i16, end: i16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const SDL_HapticRamp = struct_SDL_HapticRamp; pub const struct_SDL_HapticLeftRight = extern struct { type: u16, length: u32, large_magnitude: u16, small_magnitude: u16, }; pub const SDL_HapticLeftRight = struct_SDL_HapticLeftRight; pub const struct_SDL_HapticCustom = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, channels: u8, period: u16, samples: u16, data: [*c]u16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const SDL_HapticCustom = struct_SDL_HapticCustom; pub const union_SDL_HapticEffect = extern union { type: u16, constant: SDL_HapticConstant, periodic: SDL_HapticPeriodic, condition: SDL_HapticCondition, ramp: SDL_HapticRamp, leftright: SDL_HapticLeftRight, custom: SDL_HapticCustom, }; pub const SDL_HapticEffect = union_SDL_HapticEffect; pub extern fn SDL_NumHaptics() c_int; pub extern fn SDL_HapticName(device_index: c_int) [*c]const u8; pub extern fn SDL_HapticOpen(device_index: c_int) ?*SDL_Haptic; pub extern fn SDL_HapticOpened(device_index: c_int) c_int; pub extern fn SDL_HapticIndex(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_MouseIsHaptic() c_int; pub extern fn SDL_HapticOpenFromMouse() ?*SDL_Haptic; pub extern fn SDL_JoystickIsHaptic(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_HapticOpenFromJoystick(joystick: ?*SDL_Joystick) ?*SDL_Haptic; pub extern fn SDL_HapticClose(haptic: ?*SDL_Haptic) void; pub extern fn SDL_HapticNumEffects(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticNumEffectsPlaying(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticQuery(haptic: ?*SDL_Haptic) c_uint; pub extern fn SDL_HapticNumAxes(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticEffectSupported(haptic: ?*SDL_Haptic, effect: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticNewEffect(haptic: ?*SDL_Haptic, effect: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticUpdateEffect(haptic: ?*SDL_Haptic, effect: c_int, data: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticRunEffect(haptic: ?*SDL_Haptic, effect: c_int, iterations: u32) c_int; pub extern fn SDL_HapticStopEffect(haptic: ?*SDL_Haptic, effect: c_int) c_int; pub extern fn SDL_HapticDestroyEffect(haptic: ?*SDL_Haptic, effect: c_int) void; pub extern fn SDL_HapticGetEffectStatus(haptic: ?*SDL_Haptic, effect: c_int) c_int; pub extern fn SDL_HapticSetGain(haptic: ?*SDL_Haptic, gain: c_int) c_int; pub extern fn SDL_HapticSetAutocenter(haptic: ?*SDL_Haptic, autocenter: c_int) c_int; pub extern fn SDL_HapticPause(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticUnpause(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticStopAll(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumbleSupported(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumbleInit(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumblePlay(haptic: ?*SDL_Haptic, strength: f32, length: u32) c_int; pub extern fn SDL_HapticRumbleStop(haptic: ?*SDL_Haptic) c_int; pub const SDL_HINT_DEFAULT = @enumToInt(enum_unnamed_51.SDL_HINT_DEFAULT); pub const SDL_HINT_NORMAL = @enumToInt(enum_unnamed_51.SDL_HINT_NORMAL); pub const SDL_HINT_OVERRIDE = @enumToInt(enum_unnamed_51.SDL_HINT_OVERRIDE); const enum_unnamed_51 = extern enum(c_int) { SDL_HINT_DEFAULT, SDL_HINT_NORMAL, SDL_HINT_OVERRIDE, _, }; pub const SDL_HintPriority = enum_unnamed_51; pub extern fn SDL_SetHintWithPriority(name: [*c]const u8, value: [*c]const u8, priority: SDL_HintPriority) SDL_bool; pub extern fn SDL_SetHint(name: [*c]const u8, value: [*c]const u8) SDL_bool; pub extern fn SDL_GetHint(name: [*c]const u8) [*c]const u8; pub extern fn SDL_GetHintBoolean(name: [*c]const u8, default_value: SDL_bool) SDL_bool; pub const SDL_HintCallback = ?fn (?*c_void, [*c]const u8, [*c]const u8, [*c]const u8) callconv(.C) void; pub extern fn SDL_AddHintCallback(name: [*c]const u8, callback: SDL_HintCallback, userdata: ?*c_void) void; pub extern fn SDL_DelHintCallback(name: [*c]const u8, callback: SDL_HintCallback, userdata: ?*c_void) void; pub extern fn SDL_ClearHints() void; pub extern fn SDL_LoadObject(sofile: [*c]const u8) ?*c_void; pub extern fn SDL_LoadFunction(handle: ?*c_void, name: [*c]const u8) ?*c_void; pub extern fn SDL_UnloadObject(handle: ?*c_void) void; pub const SDL_LOG_CATEGORY_APPLICATION = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_APPLICATION); pub const SDL_LOG_CATEGORY_ERROR = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_ERROR); pub const SDL_LOG_CATEGORY_ASSERT = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_ASSERT); pub const SDL_LOG_CATEGORY_SYSTEM = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_SYSTEM); pub const SDL_LOG_CATEGORY_AUDIO = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_AUDIO); pub const SDL_LOG_CATEGORY_VIDEO = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_VIDEO); pub const SDL_LOG_CATEGORY_RENDER = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RENDER); pub const SDL_LOG_CATEGORY_INPUT = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_INPUT); pub const SDL_LOG_CATEGORY_TEST = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_TEST); pub const SDL_LOG_CATEGORY_RESERVED1 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED1); pub const SDL_LOG_CATEGORY_RESERVED2 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED2); pub const SDL_LOG_CATEGORY_RESERVED3 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED3); pub const SDL_LOG_CATEGORY_RESERVED4 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED4); pub const SDL_LOG_CATEGORY_RESERVED5 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED5); pub const SDL_LOG_CATEGORY_RESERVED6 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED6); pub const SDL_LOG_CATEGORY_RESERVED7 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED7); pub const SDL_LOG_CATEGORY_RESERVED8 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED8); pub const SDL_LOG_CATEGORY_RESERVED9 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED9); pub const SDL_LOG_CATEGORY_RESERVED10 = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_RESERVED10); pub const SDL_LOG_CATEGORY_CUSTOM = @enumToInt(enum_unnamed_52.SDL_LOG_CATEGORY_CUSTOM); const enum_unnamed_52 = extern enum(c_int) { SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_CATEGORY_ERROR, SDL_LOG_CATEGORY_ASSERT, SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_CATEGORY_AUDIO, SDL_LOG_CATEGORY_VIDEO, SDL_LOG_CATEGORY_RENDER, SDL_LOG_CATEGORY_INPUT, SDL_LOG_CATEGORY_TEST, SDL_LOG_CATEGORY_RESERVED1, SDL_LOG_CATEGORY_RESERVED2, SDL_LOG_CATEGORY_RESERVED3, SDL_LOG_CATEGORY_RESERVED4, SDL_LOG_CATEGORY_RESERVED5, SDL_LOG_CATEGORY_RESERVED6, SDL_LOG_CATEGORY_RESERVED7, SDL_LOG_CATEGORY_RESERVED8, SDL_LOG_CATEGORY_RESERVED9, SDL_LOG_CATEGORY_RESERVED10, SDL_LOG_CATEGORY_CUSTOM, _, }; pub const SDL_LogCategory = enum_unnamed_52; pub const SDL_LOG_PRIORITY_VERBOSE = @enumToInt(enum_unnamed_53.SDL_LOG_PRIORITY_VERBOSE); pub const SDL_LOG_PRIORITY_DEBUG = @enumToInt(enum_unnamed_53.SDL_LOG_PRIORITY_DEBUG); pub const SDL_LOG_PRIORITY_INFO = @enumToInt(enum_unnamed_53.SDL_LOG_PRIORITY_INFO); pub const SDL_LOG_PRIORITY_WARN = @enumToInt(enum_unnamed_53.SDL_LOG_PRIORITY_WARN); pub const SDL_LOG_PRIORITY_ERROR = @enumToInt(enum_unnamed_53.SDL_LOG_PRIORITY_ERROR); pub const SDL_LOG_PRIORITY_CRITICAL = @enumToInt(enum_unnamed_53.SDL_LOG_PRIORITY_CRITICAL); pub const SDL_NUM_LOG_PRIORITIES = @enumToInt(enum_unnamed_53.SDL_NUM_LOG_PRIORITIES); const enum_unnamed_53 = extern enum(c_int) { SDL_LOG_PRIORITY_VERBOSE = 1, SDL_LOG_PRIORITY_DEBUG = 2, SDL_LOG_PRIORITY_INFO = 3, SDL_LOG_PRIORITY_WARN = 4, SDL_LOG_PRIORITY_ERROR = 5, SDL_LOG_PRIORITY_CRITICAL = 6, SDL_NUM_LOG_PRIORITIES = 7, _, }; pub const SDL_LogPriority = enum_unnamed_53; pub extern fn SDL_LogSetAllPriority(priority: SDL_LogPriority) void; pub extern fn SDL_LogSetPriority(category: c_int, priority: SDL_LogPriority) void; pub extern fn SDL_LogGetPriority(category: c_int) SDL_LogPriority; pub extern fn SDL_LogResetPriorities() void; pub extern fn SDL_Log(fmt: [*c]const u8, ...) void; pub extern fn SDL_LogVerbose(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogDebug(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogInfo(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogWarn(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogError(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogCritical(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogMessage(category: c_int, priority: SDL_LogPriority, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogMessageV(category: c_int, priority: SDL_LogPriority, fmt: [*c]const u8, ap: [*c]struct___va_list_tag) void; pub const SDL_LogOutputFunction = ?fn (?*c_void, c_int, SDL_LogPriority, [*c]const u8) callconv(.C) void; pub extern fn SDL_LogGetOutputFunction(callback: [*c]SDL_LogOutputFunction, userdata: [*c]?*c_void) void; pub extern fn SDL_LogSetOutputFunction(callback: SDL_LogOutputFunction, userdata: ?*c_void) void; pub const SDL_MESSAGEBOX_ERROR = @enumToInt(enum_unnamed_54.SDL_MESSAGEBOX_ERROR); pub const SDL_MESSAGEBOX_WARNING = @enumToInt(enum_unnamed_54.SDL_MESSAGEBOX_WARNING); pub const SDL_MESSAGEBOX_INFORMATION = @enumToInt(enum_unnamed_54.SDL_MESSAGEBOX_INFORMATION); pub const SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT = @enumToInt(enum_unnamed_54.SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT); pub const SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT = @enumToInt(enum_unnamed_54.SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT); const enum_unnamed_54 = extern enum(c_int) { SDL_MESSAGEBOX_ERROR = 16, SDL_MESSAGEBOX_WARNING = 32, SDL_MESSAGEBOX_INFORMATION = 64, SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT = 128, SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT = 256, _, }; pub const SDL_MessageBoxFlags = enum_unnamed_54; pub const SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = @enumToInt(enum_unnamed_55.SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT); pub const SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = @enumToInt(enum_unnamed_55.SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT); const enum_unnamed_55 = extern enum(c_int) { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = 1, SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = 2, _, }; pub const SDL_MessageBoxButtonFlags = enum_unnamed_55; const struct_unnamed_56 = extern struct { flags: u32, buttonid: c_int, text: [*c]const u8, }; pub const SDL_MessageBoxButtonData = struct_unnamed_56; const struct_unnamed_57 = extern struct { r: u8, g: u8, b: u8, }; pub const SDL_MessageBoxColor = struct_unnamed_57; pub const SDL_MESSAGEBOX_COLOR_BACKGROUND = @enumToInt(enum_unnamed_58.SDL_MESSAGEBOX_COLOR_BACKGROUND); pub const SDL_MESSAGEBOX_COLOR_TEXT = @enumToInt(enum_unnamed_58.SDL_MESSAGEBOX_COLOR_TEXT); pub const SDL_MESSAGEBOX_COLOR_BUTTON_BORDER = @enumToInt(enum_unnamed_58.SDL_MESSAGEBOX_COLOR_BUTTON_BORDER); pub const SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND = @enumToInt(enum_unnamed_58.SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND); pub const SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED = @enumToInt(enum_unnamed_58.SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED); pub const SDL_MESSAGEBOX_COLOR_MAX = @enumToInt(enum_unnamed_58.SDL_MESSAGEBOX_COLOR_MAX); const enum_unnamed_58 = extern enum(c_int) { SDL_MESSAGEBOX_COLOR_BACKGROUND, SDL_MESSAGEBOX_COLOR_TEXT, SDL_MESSAGEBOX_COLOR_BUTTON_BORDER, SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND, SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED, SDL_MESSAGEBOX_COLOR_MAX, _, }; pub const SDL_MessageBoxColorType = enum_unnamed_58; const struct_unnamed_59 = extern struct { colors: [5]SDL_MessageBoxColor, }; pub const SDL_MessageBoxColorScheme = struct_unnamed_59; const struct_unnamed_60 = extern struct { flags: u32, window: ?*SDL_Window, title: [*c]const u8, message: [*c]const u8, numbuttons: c_int, buttons: [*c]const SDL_MessageBoxButtonData, colorScheme: [*c]const SDL_MessageBoxColorScheme, }; pub const SDL_MessageBoxData = struct_unnamed_60; pub extern fn SDL_ShowMessageBox(messageboxdata: [*c]const SDL_MessageBoxData, buttonid: [*c]c_int) c_int; pub extern fn SDL_ShowSimpleMessageBox(flags: u32, title: [*c]const u8, message: [*c]const u8, window: ?*SDL_Window) c_int; pub const SDL_MetalView = ?*c_void; pub extern fn SDL_Metal_CreateView(window: ?*SDL_Window) SDL_MetalView; pub extern fn SDL_Metal_DestroyView(view: SDL_MetalView) void; pub extern fn SDL_Metal_GetLayer(view: SDL_MetalView) ?*c_void; pub extern fn SDL_Metal_GetDrawableSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub const SDL_POWERSTATE_UNKNOWN = @enumToInt(enum_unnamed_61.SDL_POWERSTATE_UNKNOWN); pub const SDL_POWERSTATE_ON_BATTERY = @enumToInt(enum_unnamed_61.SDL_POWERSTATE_ON_BATTERY); pub const SDL_POWERSTATE_NO_BATTERY = @enumToInt(enum_unnamed_61.SDL_POWERSTATE_NO_BATTERY); pub const SDL_POWERSTATE_CHARGING = @enumToInt(enum_unnamed_61.SDL_POWERSTATE_CHARGING); pub const SDL_POWERSTATE_CHARGED = @enumToInt(enum_unnamed_61.SDL_POWERSTATE_CHARGED); const enum_unnamed_61 = extern enum(c_int) { SDL_POWERSTATE_UNKNOWN, SDL_POWERSTATE_ON_BATTERY, SDL_POWERSTATE_NO_BATTERY, SDL_POWERSTATE_CHARGING, SDL_POWERSTATE_CHARGED, _, }; pub const SDL_PowerState = enum_unnamed_61; pub extern fn SDL_GetPowerInfo(secs: [*c]c_int, pct: [*c]c_int) SDL_PowerState; pub const SDL_RENDERER_SOFTWARE = @enumToInt(enum_unnamed_62.SDL_RENDERER_SOFTWARE); pub const SDL_RENDERER_ACCELERATED = @enumToInt(enum_unnamed_62.SDL_RENDERER_ACCELERATED); pub const SDL_RENDERER_PRESENTVSYNC = @enumToInt(enum_unnamed_62.SDL_RENDERER_PRESENTVSYNC); pub const SDL_RENDERER_TARGETTEXTURE = @enumToInt(enum_unnamed_62.SDL_RENDERER_TARGETTEXTURE); const enum_unnamed_62 = extern enum(c_int) { SDL_RENDERER_SOFTWARE = 1, SDL_RENDERER_ACCELERATED = 2, SDL_RENDERER_PRESENTVSYNC = 4, SDL_RENDERER_TARGETTEXTURE = 8, _, }; pub const SDL_RendererFlags = enum_unnamed_62; pub const struct_SDL_RendererInfo = extern struct { name: [*c]const u8, flags: u32, num_texture_formats: u32, texture_formats: [16]u32, max_texture_width: c_int, max_texture_height: c_int, }; pub const SDL_RendererInfo = struct_SDL_RendererInfo; pub const SDL_ScaleModeNearest = @enumToInt(enum_unnamed_63.SDL_ScaleModeNearest); pub const SDL_ScaleModeLinear = @enumToInt(enum_unnamed_63.SDL_ScaleModeLinear); pub const SDL_ScaleModeBest = @enumToInt(enum_unnamed_63.SDL_ScaleModeBest); const enum_unnamed_63 = extern enum(c_int) { SDL_ScaleModeNearest, SDL_ScaleModeLinear, SDL_ScaleModeBest, _, }; pub const SDL_ScaleMode = enum_unnamed_63; pub const SDL_TEXTUREACCESS_STATIC = @enumToInt(enum_unnamed_64.SDL_TEXTUREACCESS_STATIC); pub const SDL_TEXTUREACCESS_STREAMING = @enumToInt(enum_unnamed_64.SDL_TEXTUREACCESS_STREAMING); pub const SDL_TEXTUREACCESS_TARGET = @enumToInt(enum_unnamed_64.SDL_TEXTUREACCESS_TARGET); const enum_unnamed_64 = extern enum(c_int) { SDL_TEXTUREACCESS_STATIC, SDL_TEXTUREACCESS_STREAMING, SDL_TEXTUREACCESS_TARGET, _, }; pub const SDL_TextureAccess = enum_unnamed_64; pub const SDL_TEXTUREMODULATE_NONE = @enumToInt(enum_unnamed_65.SDL_TEXTUREMODULATE_NONE); pub const SDL_TEXTUREMODULATE_COLOR = @enumToInt(enum_unnamed_65.SDL_TEXTUREMODULATE_COLOR); pub const SDL_TEXTUREMODULATE_ALPHA = @enumToInt(enum_unnamed_65.SDL_TEXTUREMODULATE_ALPHA); const enum_unnamed_65 = extern enum(c_int) { SDL_TEXTUREMODULATE_NONE = 0, SDL_TEXTUREMODULATE_COLOR = 1, SDL_TEXTUREMODULATE_ALPHA = 2, _, }; pub const SDL_TextureModulate = enum_unnamed_65; pub const SDL_FLIP_NONE = @enumToInt(enum_unnamed_66.SDL_FLIP_NONE); pub const SDL_FLIP_HORIZONTAL = @enumToInt(enum_unnamed_66.SDL_FLIP_HORIZONTAL); pub const SDL_FLIP_VERTICAL = @enumToInt(enum_unnamed_66.SDL_FLIP_VERTICAL); const enum_unnamed_66 = extern enum(c_int) { SDL_FLIP_NONE = 0, SDL_FLIP_HORIZONTAL = 1, SDL_FLIP_VERTICAL = 2, _, }; pub const SDL_RendererFlip = enum_unnamed_66; pub const struct_SDL_Renderer = opaque {}; pub const SDL_Renderer = struct_SDL_Renderer; pub const struct_SDL_Texture = opaque {}; pub const SDL_Texture = struct_SDL_Texture; pub extern fn SDL_GetNumRenderDrivers() c_int; pub extern fn SDL_GetRenderDriverInfo(index: c_int, info: [*c]SDL_RendererInfo) c_int; pub extern fn SDL_CreateWindowAndRenderer(width: c_int, height: c_int, window_flags: u32, window: [*c]?*SDL_Window, renderer: [*c]?*SDL_Renderer) c_int; pub extern fn SDL_CreateRenderer(window: ?*SDL_Window, index: c_int, flags: u32) ?*SDL_Renderer; pub extern fn SDL_CreateSoftwareRenderer(surface: [*c]SDL_Surface) ?*SDL_Renderer; pub extern fn SDL_GetRenderer(window: ?*SDL_Window) ?*SDL_Renderer; pub extern fn SDL_GetRendererInfo(renderer: ?*SDL_Renderer, info: [*c]SDL_RendererInfo) c_int; pub extern fn SDL_GetRendererOutputSize(renderer: ?*SDL_Renderer, w: [*c]c_int, h: [*c]c_int) c_int; pub extern fn SDL_CreateTexture(renderer: ?*SDL_Renderer, format: u32, access: c_int, w: c_int, h: c_int) ?*SDL_Texture; pub extern fn SDL_CreateTextureFromSurface(renderer: ?*SDL_Renderer, surface: [*c]SDL_Surface) ?*SDL_Texture; pub extern fn SDL_QueryTexture(texture: ?*SDL_Texture, format: [*c]u32, access: [*c]c_int, w: [*c]c_int, h: [*c]c_int) c_int; pub extern fn SDL_SetTextureColorMod(texture: ?*SDL_Texture, r: u8, g: u8, b: u8) c_int; pub extern fn SDL_GetTextureColorMod(texture: ?*SDL_Texture, r: [*c]u8, g: [*c]u8, b: [*c]u8) c_int; pub extern fn SDL_SetTextureAlphaMod(texture: ?*SDL_Texture, alpha: u8) c_int; pub extern fn SDL_GetTextureAlphaMod(texture: ?*SDL_Texture, alpha: [*c]u8) c_int; pub extern fn SDL_SetTextureBlendMode(texture: ?*SDL_Texture, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetTextureBlendMode(texture: ?*SDL_Texture, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_SetTextureScaleMode(texture: ?*SDL_Texture, scaleMode: SDL_ScaleMode) c_int; pub extern fn SDL_GetTextureScaleMode(texture: ?*SDL_Texture, scaleMode: [*c]SDL_ScaleMode) c_int; pub extern fn SDL_UpdateTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, pixels: ?*const c_void, pitch: c_int) c_int; pub extern fn SDL_UpdateYUVTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, Yplane: [*c]const u8, Ypitch: c_int, Uplane: [*c]const u8, Upitch: c_int, Vplane: [*c]const u8, Vpitch: c_int) c_int; pub extern fn SDL_LockTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, pixels: [*c]?*c_void, pitch: [*c]c_int) c_int; pub extern fn SDL_LockTextureToSurface(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, surface: [*c][*c]SDL_Surface) c_int; pub extern fn SDL_UnlockTexture(texture: ?*SDL_Texture) void; pub extern fn SDL_RenderTargetSupported(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_SetRenderTarget(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture) c_int; pub extern fn SDL_GetRenderTarget(renderer: ?*SDL_Renderer) ?*SDL_Texture; pub extern fn SDL_RenderSetLogicalSize(renderer: ?*SDL_Renderer, w: c_int, h: c_int) c_int; pub extern fn SDL_RenderGetLogicalSize(renderer: ?*SDL_Renderer, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_RenderSetIntegerScale(renderer: ?*SDL_Renderer, enable: SDL_bool) c_int; pub extern fn SDL_RenderGetIntegerScale(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_RenderSetViewport(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderGetViewport(renderer: ?*SDL_Renderer, rect: [*c]SDL_Rect) void; pub extern fn SDL_RenderSetClipRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderGetClipRect(renderer: ?*SDL_Renderer, rect: [*c]SDL_Rect) void; pub extern fn SDL_RenderIsClipEnabled(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_RenderSetScale(renderer: ?*SDL_Renderer, scaleX: f32, scaleY: f32) c_int; pub extern fn SDL_RenderGetScale(renderer: ?*SDL_Renderer, scaleX: [*c]f32, scaleY: [*c]f32) void; pub extern fn SDL_SetRenderDrawColor(renderer: ?*SDL_Renderer, r: u8, g: u8, b: u8, a: u8) c_int; pub extern fn SDL_GetRenderDrawColor(renderer: ?*SDL_Renderer, r: [*c]u8, g: [*c]u8, b: [*c]u8, a: [*c]u8) c_int; pub extern fn SDL_SetRenderDrawBlendMode(renderer: ?*SDL_Renderer, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetRenderDrawBlendMode(renderer: ?*SDL_Renderer, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_RenderClear(renderer: ?*SDL_Renderer) c_int; pub extern fn SDL_RenderDrawPoint(renderer: ?*SDL_Renderer, x: c_int, y: c_int) c_int; pub extern fn SDL_RenderDrawPoints(renderer: ?*SDL_Renderer, points: [*c]const SDL_Point, count: c_int) c_int; pub extern fn SDL_RenderDrawLine(renderer: ?*SDL_Renderer, x1: c_int, y1: c_int, x2: c_int, y2: c_int) c_int; pub extern fn SDL_RenderDrawLines(renderer: ?*SDL_Renderer, points: [*c]const SDL_Point, count: c_int) c_int; pub extern fn SDL_RenderDrawRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderDrawRects(renderer: ?*SDL_Renderer, rects: [*c]const SDL_Rect, count: c_int) c_int; pub extern fn SDL_RenderFillRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderFillRects(renderer: ?*SDL_Renderer, rects: [*c]const SDL_Rect, count: c_int) c_int; pub extern fn SDL_RenderCopy(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderCopyEx(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_Rect, angle: f64, center: [*c]const SDL_Point, flip: SDL_RendererFlip) c_int; pub extern fn SDL_RenderDrawPointF(renderer: ?*SDL_Renderer, x: f32, y: f32) c_int; pub extern fn SDL_RenderDrawPointsF(renderer: ?*SDL_Renderer, points: [*c]const SDL_FPoint, count: c_int) c_int; pub extern fn SDL_RenderDrawLineF(renderer: ?*SDL_Renderer, x1: f32, y1: f32, x2: f32, y2: f32) c_int; pub extern fn SDL_RenderDrawLinesF(renderer: ?*SDL_Renderer, points: [*c]const SDL_FPoint, count: c_int) c_int; pub extern fn SDL_RenderDrawRectF(renderer: ?*SDL_Renderer, rect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderDrawRectsF(renderer: ?*SDL_Renderer, rects: [*c]const SDL_FRect, count: c_int) c_int; pub extern fn SDL_RenderFillRectF(renderer: ?*SDL_Renderer, rect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderFillRectsF(renderer: ?*SDL_Renderer, rects: [*c]const SDL_FRect, count: c_int) c_int; pub extern fn SDL_RenderCopyF(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderCopyExF(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_FRect, angle: f64, center: [*c]const SDL_FPoint, flip: SDL_RendererFlip) c_int; pub extern fn SDL_RenderReadPixels(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect, format: u32, pixels: ?*c_void, pitch: c_int) c_int; pub extern fn SDL_RenderPresent(renderer: ?*SDL_Renderer) void; pub extern fn SDL_DestroyTexture(texture: ?*SDL_Texture) void; pub extern fn SDL_DestroyRenderer(renderer: ?*SDL_Renderer) void; pub extern fn SDL_RenderFlush(renderer: ?*SDL_Renderer) c_int; pub extern fn SDL_GL_BindTexture(texture: ?*SDL_Texture, texw: [*c]f32, texh: [*c]f32) c_int; pub extern fn SDL_GL_UnbindTexture(texture: ?*SDL_Texture) c_int; pub extern fn SDL_RenderGetMetalLayer(renderer: ?*SDL_Renderer) ?*c_void; pub extern fn SDL_RenderGetMetalCommandEncoder(renderer: ?*SDL_Renderer) ?*c_void; pub extern fn SDL_CreateShapedWindow(title: [*c]const u8, x: c_uint, y: c_uint, w: c_uint, h: c_uint, flags: u32) ?*SDL_Window; pub extern fn SDL_IsShapedWindow(window: ?*const SDL_Window) SDL_bool; pub const ShapeModeDefault = @enumToInt(enum_unnamed_67.ShapeModeDefault); pub const ShapeModeBinarizeAlpha = @enumToInt(enum_unnamed_67.ShapeModeBinarizeAlpha); pub const ShapeModeReverseBinarizeAlpha = @enumToInt(enum_unnamed_67.ShapeModeReverseBinarizeAlpha); pub const ShapeModeColorKey = @enumToInt(enum_unnamed_67.ShapeModeColorKey); const enum_unnamed_67 = extern enum(c_int) { ShapeModeDefault, ShapeModeBinarizeAlpha, ShapeModeReverseBinarizeAlpha, ShapeModeColorKey, _, }; pub const WindowShapeMode = enum_unnamed_67; const union_unnamed_68 = extern union { binarizationCutoff: u8, colorKey: SDL_Color, }; pub const SDL_WindowShapeParams = union_unnamed_68; pub const struct_SDL_WindowShapeMode = extern struct { mode: WindowShapeMode, parameters: SDL_WindowShapeParams, }; pub const SDL_WindowShapeMode = struct_SDL_WindowShapeMode; pub extern fn SDL_SetWindowShape(window: ?*SDL_Window, shape: [*c]SDL_Surface, shape_mode: [*c]SDL_WindowShapeMode) c_int; pub extern fn SDL_GetShapedWindowMode(window: ?*SDL_Window, shape_mode: [*c]SDL_WindowShapeMode) c_int; pub extern fn SDL_LinuxSetThreadPriority(threadID: i64, priority: c_int) c_int; pub extern fn SDL_IsTablet() SDL_bool; pub extern fn SDL_OnApplicationWillTerminate() void; pub extern fn SDL_OnApplicationDidReceiveMemoryWarning() void; pub extern fn SDL_OnApplicationWillResignActive() void; pub extern fn SDL_OnApplicationDidEnterBackground() void; pub extern fn SDL_OnApplicationWillEnterForeground() void; pub extern fn SDL_OnApplicationDidBecomeActive() void; pub extern fn SDL_GetTicks() u32; pub extern fn SDL_GetPerformanceCounter() u64; pub extern fn SDL_GetPerformanceFrequency() u64; pub extern fn SDL_Delay(ms: u32) void; pub const SDL_TimerCallback = ?fn (u32, ?*c_void) callconv(.C) u32; pub const SDL_TimerID = c_int; pub extern fn SDL_AddTimer(interval: u32, callback: SDL_TimerCallback, param: ?*c_void) SDL_TimerID; pub extern fn SDL_RemoveTimer(id: SDL_TimerID) SDL_bool; pub const struct_SDL_version = extern struct { major: u8, minor: u8, patch: u8, }; pub const SDL_version = struct_SDL_version; pub extern fn SDL_GetVersion(ver: [*c]SDL_version) void; pub extern fn SDL_GetRevision() [*c]const u8; pub extern fn SDL_GetRevisionNumber() c_int; pub const struct_SDL_Locale = extern struct { language: [*c]const u8, country: [*c]const u8, }; pub const SDL_Locale = struct_SDL_Locale; pub extern fn SDL_GetPreferredLocales() [*c]SDL_Locale; pub extern fn SDL_OpenURL(url: [*c]const u8) c_int; pub extern fn SDL_Init(flags: u32) c_int; pub extern fn SDL_InitSubSystem(flags: u32) c_int; pub extern fn SDL_QuitSubSystem(flags: u32) void; pub extern fn SDL_WasInit(flags: u32) u32; pub extern fn SDL_Quit() void; pub const SDL_DISABLE_MMINTRIN_H = 0; pub const SDL_DISABLE_XMMINTRIN_H = 0; pub const SDL_DISABLE_EMMINTRIN_H = 0; pub const SDL_DISABLE_PMMINTRIN_H = 0; pub const SDL_DISABLE_IMMINTRIN_H = 0; pub const SDL_DISABLE_MM3DNOW_H = 0; pub const SIZEOF_VOIDP = 8; pub const SDL_AUDIO_DRIVER_ALSA = 1; pub const SDL_AUDIO_DRIVER_ALSA_DYNAMIC = "libasound.so.2"; pub const SDL_AUDIO_DRIVER_DISK = 1; pub const SDL_AUDIO_DRIVER_DUMMY = 1; pub const SDL_AUDIO_DRIVER_JACK = 1; pub const SDL_AUDIO_DRIVER_JACK_DYNAMIC = "libjack.so.0"; pub const SDL_AUDIO_DRIVER_OSS = 1; pub const SDL_AUDIO_DRIVER_PULSEAUDIO = 1; pub const SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC = "libpulse-simple.so.0"; pub const SDL_INPUT_LINUXEV = 1; pub const SDL_INPUT_LINUXKD = 1; pub const SDL_JOYSTICK_LINUX = 1; pub const SDL_JOYSTICK_HIDAPI = 1; pub const SDL_JOYSTICK_VIRTUAL = 1; pub const SDL_HAPTIC_LINUX = 1; pub const SDL_SENSOR_DUMMY = 1; pub const SDL_LOADSO_DLOPEN = 1; pub const SDL_THREAD_PTHREAD = 1; pub const SDL_THREAD_PTHREAD_RECURSIVE_MUTEX = 1; pub const SDL_TIMER_UNIX = 1; pub const SDL_VIDEO_DRIVER_DUMMY = 1; pub const SDL_VIDEO_DRIVER_WAYLAND = 1; pub const SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH = 1; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC = "libwayland-client.so.0"; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL = "libwayland-egl.so.1"; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR = "libwayland-cursor.so.0"; pub const SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON = "libxkbcommon.so.0"; pub const SDL_VIDEO_DRIVER_X11 = 1; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC = "libX11.so.6"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT = "libXext.so.6"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR = "libXcursor.so.1"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA = "libXinerama.so.1"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 = "libXi.so.6"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR = "libXrandr.so.2"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS = "libXss.so.1"; pub const SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE = "libXxf86vm.so.1"; pub const SDL_VIDEO_DRIVER_X11_XCURSOR = 1; pub const SDL_VIDEO_DRIVER_X11_XDBE = 1; pub const SDL_VIDEO_DRIVER_X11_XINERAMA = 1; pub const SDL_VIDEO_DRIVER_X11_XINPUT2 = 1; pub const SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH = 1; pub const SDL_VIDEO_DRIVER_X11_XRANDR = 1; pub const SDL_VIDEO_DRIVER_X11_XSCRNSAVER = 1; pub const SDL_VIDEO_DRIVER_X11_XSHAPE = 1; pub const SDL_VIDEO_DRIVER_X11_XVIDMODE = 1; pub const SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS = 1; pub const SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY = 1; pub const SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM = 1; pub const SDL_VIDEO_RENDER_OGL = 1; pub const SDL_VIDEO_RENDER_OGL_ES2 = 1; pub const SDL_VIDEO_OPENGL = 1; pub const SDL_VIDEO_OPENGL_ES2 = 1; pub const SDL_VIDEO_OPENGL_EGL = 1; pub const SDL_VIDEO_OPENGL_GLX = 1; pub const SDL_VIDEO_VULKAN = 1; pub const SDL_POWER_LINUX = 1; pub const SDL_FILESYSTEM_UNIX = 1; pub const SDL_ASSEMBLY_ROUTINES = 1; pub const SDL_USE_IME = 1; pub const SDL_UDEV_DYNAMIC = "libudev.so.1"; pub const SDL_LIBSAMPLERATE_DYNAMIC = "libsamplerate.so.0"; pub inline fn offsetof(t: anytype, d: anytype) @TypeOf(__builtin_offsetof(t, d)) { return __builtin_offsetof(t, d); } pub inline fn va_start(ap: anytype, param: anytype) @TypeOf(__builtin_va_start(ap, param)) { return __builtin_va_start(ap, param); } pub inline fn va_end(ap: anytype) @TypeOf(__builtin_va_end(ap)) { return __builtin_va_end(ap); } pub inline fn va_arg(ap: anytype, type_1: anytype) @TypeOf(__builtin_va_arg(ap, type_1)) { return __builtin_va_arg(ap, type_1); } pub inline fn __va_copy(d: anytype, s: anytype) @TypeOf(__builtin_va_copy(d, s)) { return __builtin_va_copy(d, s); } pub inline fn va_copy(dest: anytype, src: anytype) @TypeOf(__builtin_va_copy(dest, src)) { return __builtin_va_copy(dest, src); } pub inline fn __int_c(v: anytype, suffix: anytype) @TypeOf(__int_c_join(v, suffix)) { return __int_c_join(v, suffix); } pub inline fn INT64_C(v: anytype) @TypeOf(__int_c(v, __int64_c_suffix)) { return __int_c(v, __int64_c_suffix); } pub inline fn UINT64_C(v: anytype) @TypeOf(__uint_c(v, __int64_c_suffix)) { return __uint_c(v, __int64_c_suffix); } pub inline fn INT32_C(v: anytype) @TypeOf(__int_c(v, __int32_c_suffix)) { return __int_c(v, __int32_c_suffix); } pub inline fn UINT32_C(v: anytype) @TypeOf(__uint_c(v, __int32_c_suffix)) { return __uint_c(v, __int32_c_suffix); } pub inline fn INT16_C(v: anytype) @TypeOf(__int_c(v, __int16_c_suffix)) { return __int_c(v, __int16_c_suffix); } pub inline fn UINT16_C(v: anytype) @TypeOf(__uint_c(v, __int16_c_suffix)) { return __uint_c(v, __int16_c_suffix); } pub inline fn INT8_C(v: anytype) @TypeOf(__int_c(v, __int8_c_suffix)) { return __int_c(v, __int8_c_suffix); } pub inline fn UINT8_C(v: anytype) @TypeOf(__uint_c(v, __int8_c_suffix)) { return __uint_c(v, __int8_c_suffix); } pub inline fn __INTN_MIN(n: anytype) @TypeOf(__stdint_join3(INT, n, _MIN)) { return __stdint_join3(INT, n, _MIN); } pub inline fn __INTN_MAX(n: anytype) @TypeOf(__stdint_join3(INT, n, _MAX)) { return __stdint_join3(INT, n, _MAX); } pub inline fn __UINTN_MAX(n: anytype) @TypeOf(__stdint_join3(UINT, n, _MAX)) { return __stdint_join3(UINT, n, _MAX); } pub inline fn __INTN_C(n: anytype, v: anytype) @TypeOf(__stdint_join3(INT, n, _C(v))) { return __stdint_join3(INT, n, _C(v)); } pub inline fn __UINTN_C(n: anytype, v: anytype) @TypeOf(__stdint_join3(UINT, n, _C(v))) { return __stdint_join3(UINT, n, _C(v)); } pub inline fn INTMAX_C(v: anytype) @TypeOf(__int_c(v, __INTMAX_C_SUFFIX__)) { return __int_c(v, __INTMAX_C_SUFFIX__); } pub inline fn UINTMAX_C(v: anytype) @TypeOf(__int_c(v, __UINTMAX_C_SUFFIX__)) { return __int_c(v, __UINTMAX_C_SUFFIX__); } pub inline fn SDL_arraysize(array: anytype) @TypeOf(@import("std").meta.sizeof(array) / @import("std").meta.sizeof(array[0])) { return @import("std").meta.sizeof(array) / @import("std").meta.sizeof(array[0]); } pub inline fn SDL_TABLESIZE(table: anytype) @TypeOf(SDL_arraysize(table)) { return SDL_arraysize(table); } pub inline fn SDL_reinterpret_cast(type_1: anytype, expression: anytype) @TypeOf((@import("std").meta.cast(type_1, expression))) { return (@import("std").meta.cast(type_1, expression)); } pub inline fn SDL_static_cast(type_1: anytype, expression: anytype) @TypeOf((@import("std").meta.cast(type_1, expression))) { return (@import("std").meta.cast(type_1, expression)); } pub inline fn SDL_const_cast(type_1: anytype, expression: anytype) @TypeOf((@import("std").meta.cast(type_1, expression))) { return (@import("std").meta.cast(type_1, expression)); } pub inline fn SDL_FOURCC(A: anytype, B: anytype, C: anytype, D: anytype) @TypeOf((((SDL_static_cast(u32, SDL_static_cast(u8, A)) << 0) | (SDL_static_cast(u32, SDL_static_cast(u8, B)) << 8)) | (SDL_static_cast(u32, SDL_static_cast(u8, C)) << 16)) | (SDL_static_cast(u32, SDL_static_cast(u8, D)) << 24)) { return (((SDL_static_cast(u32, SDL_static_cast(u8, A)) << 0) | (SDL_static_cast(u32, SDL_static_cast(u8, B)) << 8)) | (SDL_static_cast(u32, SDL_static_cast(u8, C)) << 16)) | (SDL_static_cast(u32, SDL_static_cast(u8, D)) << 24); } pub inline fn SDL_PRINTF_VARARG_FUNC(fmtargnumber: anytype) @TypeOf(__attribute__(format(__printf__, fmtargnumber, fmtargnumber + 1))) { return __attribute__(format(__printf__, fmtargnumber, fmtargnumber + 1)); } pub inline fn SDL_SCANF_VARARG_FUNC(fmtargnumber: anytype) @TypeOf(__attribute__(format(__scanf__, fmtargnumber, fmtargnumber + 1))) { return __attribute__(format(__scanf__, fmtargnumber, fmtargnumber + 1)); } pub inline fn SDL_stack_alloc(type_1: anytype, count: anytype) @TypeOf((@import("std").meta.cast([*c]type_1, alloca(@import("std").meta.sizeof(type_1) * count)))) { return (@import("std").meta.cast([*c]type_1, alloca(@import("std").meta.sizeof(type_1) * count))); } pub inline fn SDL_min(x: anytype, y: anytype) @TypeOf(if (x < y) x else y) { return if (x < y) x else y; } pub inline fn SDL_max(x: anytype, y: anytype) @TypeOf(if (x > y) x else y) { return if (x > y) x else y; } pub inline fn SDL_zero(x: anytype) @TypeOf(SDL_memset(&x, 0, @import("std").meta.sizeof(x))) { return SDL_memset(&x, 0, @import("std").meta.sizeof(x)); } pub inline fn SDL_zerop(x: anytype) @TypeOf(SDL_memset(x, 0, @import("std").meta.sizeof(x.*))) { return SDL_memset(x, 0, @import("std").meta.sizeof(x.*)); } pub inline fn SDL_zeroa(x: anytype) @TypeOf(SDL_memset(x, 0, @import("std").meta.sizeof(x))) { return SDL_memset(x, 0, @import("std").meta.sizeof(x)); } pub const SDL_ICONV_ERROR = @bitCast(usize, @as(isize, -1)); pub const SDL_ICONV_E2BIG = @bitCast(usize, @as(isize, -2)); pub const SDL_ICONV_EILSEQ = @bitCast(usize, @as(isize, -3)); pub const SDL_ICONV_EINVAL = @bitCast(usize, @as(isize, -4)); pub inline fn SDL_iconv_utf8_locale(S: anytype) @TypeOf(SDL_iconv_string("", "UTF-8", S, SDL_strlen(S) + 1)) { return SDL_iconv_string("", "UTF-8", S, SDL_strlen(S) + 1); } pub inline fn SDL_iconv_utf8_ucs2(S: anytype) @TypeOf((@import("std").meta.cast([*c]u16, SDL_iconv_string("UCS-2-INTERNAL", "UTF-8", S, SDL_strlen(S) + 1)))) { return (@import("std").meta.cast([*c]u16, SDL_iconv_string("UCS-2-INTERNAL", "UTF-8", S, SDL_strlen(S) + 1))); } pub inline fn SDL_iconv_utf8_ucs4(S: anytype) @TypeOf((@import("std").meta.cast([*c]u32, SDL_iconv_string("UCS-4-INTERNAL", "UTF-8", S, SDL_strlen(S) + 1)))) { return (@import("std").meta.cast([*c]u32, SDL_iconv_string("UCS-4-INTERNAL", "UTF-8", S, SDL_strlen(S) + 1))); } pub const SDL_ASSERT_LEVEL = 2; pub const SDL_NULL_WHILE_LOOP_CONDITION = 0; pub inline fn SDL_assert(condition: anytype) @TypeOf(SDL_enabled_assert(condition)) { return SDL_enabled_assert(condition); } pub inline fn SDL_assert_release(condition: anytype) @TypeOf(SDL_enabled_assert(condition)) { return SDL_enabled_assert(condition); } pub inline fn SDL_assert_paranoid(condition: anytype) @TypeOf(SDL_disabled_assert(condition)) { return SDL_disabled_assert(condition); } pub inline fn SDL_assert_always(condition: anytype) @TypeOf(SDL_enabled_assert(condition)) { return SDL_enabled_assert(condition); } pub const SDL_assert_state = SDL_AssertState; pub const SDL_assert_data = SDL_AssertData; pub inline fn SDL_AtomicIncRef(a: anytype) @TypeOf(SDL_AtomicAdd(a, 1)) { return SDL_AtomicAdd(a, 1); } pub inline fn SDL_AtomicDecRef(a: anytype) @TypeOf(SDL_AtomicAdd(a, -1) == 1) { return SDL_AtomicAdd(a, -1) == 1; } pub const SDL_LIL_ENDIAN = 1234; pub const SDL_BIG_ENDIAN = 4321; pub inline fn SDL_SwapLE16(X: anytype) @TypeOf(SDL_Swap16(X)) { return SDL_Swap16(X); } pub inline fn SDL_SwapLE32(X: anytype) @TypeOf(SDL_Swap32(X)) { return SDL_Swap32(X); } pub inline fn SDL_SwapLE64(X: anytype) @TypeOf(SDL_Swap64(X)) { return SDL_Swap64(X); } pub inline fn SDL_SwapFloatLE(X: anytype) @TypeOf(SDL_SwapFloat(X)) { return SDL_SwapFloat(X); } pub inline fn SDL_SwapBE16(X: anytype) @TypeOf(X) { return X; } pub inline fn SDL_SwapBE32(X: anytype) @TypeOf(X) { return X; } pub inline fn SDL_SwapBE64(X: anytype) @TypeOf(X) { return X; } pub inline fn SDL_SwapFloatBE(X: anytype) @TypeOf(X) { return X; } pub const SDL_MUTEX_TIMEDOUT = 1; pub const SDL_MUTEX_MAXWAIT = ~(@import("std").meta.cast(u32, 0)); pub inline fn SDL_mutexP(m: anytype) @TypeOf(SDL_LockMutex(m)) { return SDL_LockMutex(m); } pub inline fn SDL_mutexV(m: anytype) @TypeOf(SDL_UnlockMutex(m)) { return SDL_UnlockMutex(m); } pub const SDL_RWOPS_UNKNOWN = @as(c_uint, 0); pub const SDL_RWOPS_WINFILE = @as(c_uint, 1); pub const SDL_RWOPS_STDFILE = @as(c_uint, 2); pub const SDL_RWOPS_JNIFILE = @as(c_uint, 3); pub const SDL_RWOPS_MEMORY = @as(c_uint, 4); pub const SDL_RWOPS_MEMORY_RO = @as(c_uint, 5); pub const RW_SEEK_SET = 0; pub const RW_SEEK_CUR = 1; pub const RW_SEEK_END = 2; pub const SDL_AUDIO_MASK_BITSIZE = 0xFF; pub const SDL_AUDIO_MASK_DATATYPE = 1 << 8; pub const SDL_AUDIO_MASK_ENDIAN = 1 << 12; pub const SDL_AUDIO_MASK_SIGNED = 1 << 15; pub inline fn SDL_AUDIO_BITSIZE(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_BITSIZE) { return x & SDL_AUDIO_MASK_BITSIZE; } pub inline fn SDL_AUDIO_ISFLOAT(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_DATATYPE) { return x & SDL_AUDIO_MASK_DATATYPE; } pub inline fn SDL_AUDIO_ISBIGENDIAN(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_ENDIAN) { return x & SDL_AUDIO_MASK_ENDIAN; } pub inline fn SDL_AUDIO_ISSIGNED(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_SIGNED) { return x & SDL_AUDIO_MASK_SIGNED; } pub inline fn SDL_AUDIO_ISINT(x: anytype) @TypeOf(!(SDL_AUDIO_ISFLOAT(x) != 0)) { return !(SDL_AUDIO_ISFLOAT(x) != 0); } pub inline fn SDL_AUDIO_ISLITTLEENDIAN(x: anytype) @TypeOf(!(SDL_AUDIO_ISBIGENDIAN(x) != 0)) { return !(SDL_AUDIO_ISBIGENDIAN(x) != 0); } pub inline fn SDL_AUDIO_ISUNSIGNED(x: anytype) @TypeOf(!(SDL_AUDIO_ISSIGNED(x) != 0)) { return !(SDL_AUDIO_ISSIGNED(x) != 0); } pub const AUDIO_U8 = 0x0008; pub const AUDIO_S8 = 0x8008; pub const AUDIO_U16LSB = 0x0010; pub const AUDIO_S16LSB = 0x8010; pub const AUDIO_U16MSB = 0x1010; pub const AUDIO_S16MSB = 0x9010; pub const AUDIO_U16 = AUDIO_U16LSB; pub const AUDIO_S16 = AUDIO_S16LSB; pub const AUDIO_S32LSB = 0x8020; pub const AUDIO_S32MSB = 0x9020; pub const AUDIO_S32 = AUDIO_S32LSB; pub const AUDIO_F32LSB = 0x8120; pub const AUDIO_F32MSB = 0x9120; pub const AUDIO_F32 = AUDIO_F32LSB; pub const AUDIO_U16SYS = AUDIO_U16MSB; pub const AUDIO_S16SYS = AUDIO_S16MSB; pub const AUDIO_S32SYS = AUDIO_S32MSB; pub const AUDIO_F32SYS = AUDIO_F32MSB; pub const SDL_AUDIO_ALLOW_FREQUENCY_CHANGE = 0x00000001; pub const SDL_AUDIO_ALLOW_FORMAT_CHANGE = 0x00000002; pub const SDL_AUDIO_ALLOW_CHANNELS_CHANGE = 0x00000004; pub const SDL_AUDIO_ALLOW_SAMPLES_CHANGE = 0x00000008; pub const SDL_AUDIO_ALLOW_ANY_CHANGE = ((SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_FORMAT_CHANGE) | SDL_AUDIO_ALLOW_CHANNELS_CHANGE) | SDL_AUDIO_ALLOW_SAMPLES_CHANGE; pub const SDL_AUDIOCVT_MAX_FILTERS = 9; pub inline fn SDL_LoadWAV(file: anytype, spec: anytype, audio_buf: anytype, audio_len: anytype) @TypeOf(SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"), 1, spec, audio_buf, audio_len)) { return SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"), 1, spec, audio_buf, audio_len); } pub const SDL_MIX_MAXVOLUME = 128; pub const SDL_CACHELINE_SIZE = 128; pub const SDL_ALPHA_OPAQUE = 255; pub const SDL_ALPHA_TRANSPARENT = 0; pub inline fn SDL_DEFINE_PIXELFOURCC(A: anytype, B: anytype, C: anytype, D: anytype) @TypeOf(SDL_FOURCC(A, B, C, D)) { return SDL_FOURCC(A, B, C, D); } pub inline fn SDL_DEFINE_PIXELFORMAT(type_1: anytype, order: anytype, layout: anytype, bits: anytype, bytes: anytype) @TypeOf((((((1 << 28) | (type_1 << 24)) | (order << 20)) | (layout << 16)) | (bits << 8)) | (bytes << 0)) { return (((((1 << 28) | (type_1 << 24)) | (order << 20)) | (layout << 16)) | (bits << 8)) | (bytes << 0); } pub inline fn SDL_PIXELFLAG(X: anytype) @TypeOf((X >> 28) & 0x0F) { return (X >> 28) & 0x0F; } pub inline fn SDL_PIXELTYPE(X: anytype) @TypeOf((X >> 24) & 0x0F) { return (X >> 24) & 0x0F; } pub inline fn SDL_PIXELORDER(X: anytype) @TypeOf((X >> 20) & 0x0F) { return (X >> 20) & 0x0F; } pub inline fn SDL_PIXELLAYOUT(X: anytype) @TypeOf((X >> 16) & 0x0F) { return (X >> 16) & 0x0F; } pub inline fn SDL_BITSPERPIXEL(X: anytype) @TypeOf((X >> 8) & 0xFF) { return (X >> 8) & 0xFF; } pub inline fn SDL_BYTESPERPIXEL(X: anytype) @TypeOf(if (SDL_ISPIXELFORMAT_FOURCC(X)) if (((X == SDL_PIXELFORMAT_YUY2) or (X == SDL_PIXELFORMAT_UYVY)) or (X == SDL_PIXELFORMAT_YVYU)) 2 else 1 else (X >> 0) & 0xFF) { return if (SDL_ISPIXELFORMAT_FOURCC(X)) if (((X == SDL_PIXELFORMAT_YUY2) or (X == SDL_PIXELFORMAT_UYVY)) or (X == SDL_PIXELFORMAT_YVYU)) 2 else 1 else (X >> 0) & 0xFF; } pub inline fn SDL_ISPIXELFORMAT_INDEXED(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8)); } pub inline fn SDL_ISPIXELFORMAT_PACKED(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32)); } pub inline fn SDL_ISPIXELFORMAT_ARRAY(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32)); } pub inline fn SDL_ISPIXELFORMAT_ALPHA(format: anytype) @TypeOf(((SDL_ISPIXELFORMAT_PACKED(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) or ((SDL_ISPIXELFORMAT_ARRAY(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA)))) { return ((SDL_ISPIXELFORMAT_PACKED(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) or ((SDL_ISPIXELFORMAT_ARRAY(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA))); } pub inline fn SDL_ISPIXELFORMAT_FOURCC(format: anytype) @TypeOf((format != 0) and (SDL_PIXELFLAG(format) != 1)) { return (format != 0) and (SDL_PIXELFLAG(format) != 1); } pub const SDL_Colour = SDL_Color; pub const SDL_SWSURFACE = 0; pub const SDL_PREALLOC = 0x00000001; pub const SDL_RLEACCEL = 0x00000002; pub const SDL_DONTFREE = 0x00000004; pub const SDL_SIMD_ALIGNED = 0x00000008; pub inline fn SDL_MUSTLOCK(S: anytype) @TypeOf(((S.*.flags) & SDL_RLEACCEL) != 0) { return ((S.*.flags) & SDL_RLEACCEL) != 0; } pub inline fn SDL_LoadBMP(file: anytype) @TypeOf(SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), 1)) { return SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), 1); } pub inline fn SDL_SaveBMP(surface: anytype, file: anytype) @TypeOf(SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), 1)) { return SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), 1); } pub const SDL_BlitSurface = SDL_UpperBlit; pub const SDL_BlitScaled = SDL_UpperBlitScaled; pub const SDL_WINDOWPOS_UNDEFINED_MASK = @as(c_uint, 0x1FFF0000); pub inline fn SDL_WINDOWPOS_UNDEFINED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_UNDEFINED_MASK | X) { return SDL_WINDOWPOS_UNDEFINED_MASK | X; } pub const SDL_WINDOWPOS_UNDEFINED = SDL_WINDOWPOS_UNDEFINED_DISPLAY(0); pub inline fn SDL_WINDOWPOS_ISUNDEFINED(X: anytype) @TypeOf((X & 0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK) { return (X & 0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK; } pub const SDL_WINDOWPOS_CENTERED_MASK = @as(c_uint, 0x2FFF0000); pub inline fn SDL_WINDOWPOS_CENTERED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_CENTERED_MASK | X) { return SDL_WINDOWPOS_CENTERED_MASK | X; } pub const SDL_WINDOWPOS_CENTERED = SDL_WINDOWPOS_CENTERED_DISPLAY(0); pub inline fn SDL_WINDOWPOS_ISCENTERED(X: anytype) @TypeOf((X & 0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK) { return (X & 0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK; } pub const SDLK_SCANCODE_MASK = 1 << 30; pub inline fn SDL_SCANCODE_TO_KEYCODE(X: anytype) @TypeOf(X | SDLK_SCANCODE_MASK) { return X | SDLK_SCANCODE_MASK; } pub inline fn SDL_BUTTON(X: anytype) @TypeOf(1 << (X - 1)) { return 1 << (X - 1); } pub const SDL_BUTTON_LEFT = 1; pub const SDL_BUTTON_MIDDLE = 2; pub const SDL_BUTTON_RIGHT = 3; pub const SDL_BUTTON_X1 = 4; pub const SDL_BUTTON_X2 = 5; pub const SDL_BUTTON_LMASK = SDL_BUTTON(SDL_BUTTON_LEFT); pub const SDL_BUTTON_MMASK = SDL_BUTTON(SDL_BUTTON_MIDDLE); pub const SDL_BUTTON_RMASK = SDL_BUTTON(SDL_BUTTON_RIGHT); pub const SDL_BUTTON_X1MASK = SDL_BUTTON(SDL_BUTTON_X1); pub const SDL_BUTTON_X2MASK = SDL_BUTTON(SDL_BUTTON_X2); pub const SDL_IPHONE_MAX_GFORCE = 5.0; pub const SDL_JOYSTICK_AXIS_MAX = 32767; pub const SDL_JOYSTICK_AXIS_MIN = -32768; pub const SDL_HAT_CENTERED = 0x00; pub const SDL_HAT_UP = 0x01; pub const SDL_HAT_RIGHT = 0x02; pub const SDL_HAT_DOWN = 0x04; pub const SDL_HAT_LEFT = 0x08; pub const SDL_HAT_RIGHTUP = SDL_HAT_RIGHT | SDL_HAT_UP; pub const SDL_HAT_RIGHTDOWN = SDL_HAT_RIGHT | SDL_HAT_DOWN; pub const SDL_HAT_LEFTUP = SDL_HAT_LEFT | SDL_HAT_UP; pub const SDL_HAT_LEFTDOWN = SDL_HAT_LEFT | SDL_HAT_DOWN; pub const SDL_STANDARD_GRAVITY = @as(f32, 9.80665); pub inline fn SDL_GameControllerAddMappingsFromFile(file: anytype) @TypeOf(SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), 1)) { return SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), 1); } pub const SDL_TOUCH_MOUSEID = @bitCast(u32, @as(i32, -1)); pub const SDL_MOUSE_TOUCHID = @as(i64, -1); pub const SDL_RELEASED = 0; pub const SDL_PRESSED = 1; pub const SDL_TEXTEDITINGEVENT_TEXT_SIZE = 32; pub const SDL_TEXTINPUTEVENT_TEXT_SIZE = 32; pub const SDL_QUERY = -1; pub const SDL_IGNORE = 0; pub const SDL_DISABLE = 0; pub const SDL_ENABLE = 1; pub inline fn SDL_GetEventState(type_1: anytype) @TypeOf(SDL_EventState(type_1, SDL_QUERY)) { return SDL_EventState(type_1, SDL_QUERY); } pub const SDL_HAPTIC_CONSTANT = @as(c_uint, 1) << 0; pub const SDL_HAPTIC_SINE = @as(c_uint, 1) << 1; pub const SDL_HAPTIC_LEFTRIGHT = @as(c_uint, 1) << 2; pub const SDL_HAPTIC_TRIANGLE = @as(c_uint, 1) << 3; pub const SDL_HAPTIC_SAWTOOTHUP = @as(c_uint, 1) << 4; pub const SDL_HAPTIC_SAWTOOTHDOWN = @as(c_uint, 1) << 5; pub const SDL_HAPTIC_RAMP = @as(c_uint, 1) << 6; pub const SDL_HAPTIC_SPRING = @as(c_uint, 1) << 7; pub const SDL_HAPTIC_DAMPER = @as(c_uint, 1) << 8; pub const SDL_HAPTIC_INERTIA = @as(c_uint, 1) << 9; pub const SDL_HAPTIC_FRICTION = @as(c_uint, 1) << 10; pub const SDL_HAPTIC_CUSTOM = @as(c_uint, 1) << 11; pub const SDL_HAPTIC_GAIN = @as(c_uint, 1) << 12; pub const SDL_HAPTIC_AUTOCENTER = @as(c_uint, 1) << 13; pub const SDL_HAPTIC_STATUS = @as(c_uint, 1) << 14; pub const SDL_HAPTIC_PAUSE = @as(c_uint, 1) << 15; pub const SDL_HAPTIC_POLAR = 0; pub const SDL_HAPTIC_CARTESIAN = 1; pub const SDL_HAPTIC_SPHERICAL = 2; pub const SDL_HAPTIC_STEERING_AXIS = 3; pub const SDL_HAPTIC_INFINITY = @as(c_uint, 4294967295); pub const SDL_HINT_FRAMEBUFFER_ACCELERATION = "SDL_FRAMEBUFFER_ACCELERATION"; pub const SDL_HINT_RENDER_DRIVER = "SDL_RENDER_DRIVER"; pub const SDL_HINT_RENDER_OPENGL_SHADERS = "SDL_RENDER_OPENGL_SHADERS"; pub const SDL_HINT_RENDER_DIRECT3D_THREADSAFE = "SDL_RENDER_DIRECT3D_THREADSAFE"; pub const SDL_HINT_RENDER_DIRECT3D11_DEBUG = "SDL_RENDER_DIRECT3D11_DEBUG"; pub const SDL_HINT_RENDER_LOGICAL_SIZE_MODE = "SDL_RENDER_LOGICAL_SIZE_MODE"; pub const SDL_HINT_RENDER_SCALE_QUALITY = "SDL_RENDER_SCALE_QUALITY"; pub const SDL_HINT_RENDER_VSYNC = "SDL_RENDER_VSYNC"; pub const SDL_HINT_VIDEO_ALLOW_SCREENSAVER = "SDL_VIDEO_ALLOW_SCREENSAVER"; pub const SDL_HINT_VIDEO_EXTERNAL_CONTEXT = "SDL_VIDEO_EXTERNAL_CONTEXT"; pub const SDL_HINT_VIDEO_X11_XVIDMODE = "SDL_VIDEO_X11_XVIDMODE"; pub const SDL_HINT_VIDEO_X11_XINERAMA = "SDL_VIDEO_X11_XINERAMA"; pub const SDL_HINT_VIDEO_X11_XRANDR = "SDL_VIDEO_X11_XRANDR"; pub const SDL_HINT_VIDEO_X11_WINDOW_VISUALID = "SDL_VIDEO_X11_WINDOW_VISUALID"; pub const SDL_HINT_VIDEO_X11_NET_WM_PING = "SDL_VIDEO_X11_NET_WM_PING"; pub const SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR = "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR"; pub const SDL_HINT_VIDEO_X11_FORCE_EGL = "SDL_VIDEO_X11_FORCE_EGL"; pub const SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN = "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN"; pub const SDL_HINT_WINDOWS_INTRESOURCE_ICON = "SDL_WINDOWS_INTRESOURCE_ICON"; pub const SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL = "SDL_WINDOWS_INTRESOURCE_ICON_SMALL"; pub const SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP = "SDL_WINDOWS_ENABLE_MESSAGELOOP"; pub const SDL_HINT_GRAB_KEYBOARD = "SDL_GRAB_KEYBOARD"; pub const SDL_HINT_MOUSE_DOUBLE_CLICK_TIME = "SDL_MOUSE_DOUBLE_CLICK_TIME"; pub const SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS = "SDL_MOUSE_DOUBLE_CLICK_RADIUS"; pub const SDL_HINT_MOUSE_NORMAL_SPEED_SCALE = "SDL_MOUSE_NORMAL_SPEED_SCALE"; pub const SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE = "SDL_MOUSE_RELATIVE_SPEED_SCALE"; pub const SDL_HINT_MOUSE_RELATIVE_SCALING = "SDL_MOUSE_RELATIVE_SCALING"; pub const SDL_HINT_MOUSE_RELATIVE_MODE_WARP = "SDL_MOUSE_RELATIVE_MODE_WARP"; pub const SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH = "SDL_MOUSE_FOCUS_CLICKTHROUGH"; pub const SDL_HINT_TOUCH_MOUSE_EVENTS = "SDL_TOUCH_MOUSE_EVENTS"; pub const SDL_HINT_MOUSE_TOUCH_EVENTS = "SDL_MOUSE_TOUCH_EVENTS"; pub const SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS = "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS"; pub const SDL_HINT_IDLE_TIMER_DISABLED = "SDL_IOS_IDLE_TIMER_DISABLED"; pub const SDL_HINT_ORIENTATIONS = "SDL_IOS_ORIENTATIONS"; pub const SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS = "SDL_APPLE_TV_CONTROLLER_UI_EVENTS"; pub const SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION = "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION"; pub const SDL_HINT_IOS_HIDE_HOME_INDICATOR = "SDL_IOS_HIDE_HOME_INDICATOR"; pub const SDL_HINT_ACCELEROMETER_AS_JOYSTICK = "SDL_ACCELEROMETER_AS_JOYSTICK"; pub const SDL_HINT_TV_REMOTE_AS_JOYSTICK = "SDL_TV_REMOTE_AS_JOYSTICK"; pub const SDL_HINT_XINPUT_ENABLED = "SDL_XINPUT_ENABLED"; pub const SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING = "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING"; pub const SDL_HINT_GAMECONTROLLERTYPE = "SDL_GAMECONTROLLERTYPE"; pub const SDL_HINT_GAMECONTROLLERCONFIG = "SDL_GAMECONTROLLERCONFIG"; pub const SDL_HINT_GAMECONTROLLERCONFIG_FILE = "SDL_GAMECONTROLLERCONFIG_FILE"; pub const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES = "SDL_GAMECONTROLLER_IGNORE_DEVICES"; pub const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT = "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"; pub const SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS = "SDL_GAMECONTROLLER_USE_BUTTON_LABELS"; pub const SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS = "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"; pub const SDL_HINT_JOYSTICK_HIDAPI = "SDL_JOYSTICK_HIDAPI"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS4 = "SDL_JOYSTICK_HIDAPI_PS4"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS4_RUMBLE"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5 = "SDL_JOYSTICK_HIDAPI_PS5"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS5_RUMBLE"; pub const SDL_HINT_JOYSTICK_HIDAPI_STEAM = "SDL_JOYSTICK_HIDAPI_STEAM"; pub const SDL_HINT_JOYSTICK_HIDAPI_SWITCH = "SDL_JOYSTICK_HIDAPI_SWITCH"; pub const SDL_HINT_JOYSTICK_HIDAPI_XBOX = "SDL_JOYSTICK_HIDAPI_XBOX"; pub const SDL_HINT_JOYSTICK_HIDAPI_CORRELATE_XINPUT = "SDL_JOYSTICK_HIDAPI_CORRELATE_XINPUT"; pub const SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE = "SDL_JOYSTICK_HIDAPI_GAMECUBE"; pub const SDL_HINT_ENABLE_STEAM_CONTROLLERS = "SDL_ENABLE_STEAM_CONTROLLERS"; pub const SDL_HINT_JOYSTICK_RAWINPUT = "SDL_JOYSTICK_RAWINPUT"; pub const SDL_HINT_JOYSTICK_THREAD = "SDL_JOYSTICK_THREAD"; pub const SDL_HINT_LINUX_JOYSTICK_DEADZONES = "SDL_LINUX_JOYSTICK_DEADZONES"; pub const SDL_HINT_ALLOW_TOPMOST = "SDL_ALLOW_TOPMOST"; pub const SDL_HINT_TIMER_RESOLUTION = "SDL_TIMER_RESOLUTION"; pub const SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION = "SDL_QTWAYLAND_CONTENT_ORIENTATION"; pub const SDL_HINT_QTWAYLAND_WINDOW_FLAGS = "SDL_QTWAYLAND_WINDOW_FLAGS"; pub const SDL_HINT_THREAD_STACK_SIZE = "SDL_THREAD_STACK_SIZE"; pub const SDL_HINT_THREAD_PRIORITY_POLICY = "SDL_THREAD_PRIORITY_POLICY"; pub const SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL = "SDL_THREAD_FORCE_REALTIME_TIME_CRITICAL"; pub const SDL_HINT_VIDEO_HIGHDPI_DISABLED = "SDL_VIDEO_HIGHDPI_DISABLED"; pub const SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK = "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK"; pub const SDL_HINT_VIDEO_WIN_D3DCOMPILER = "SDL_VIDEO_WIN_D3DCOMPILER"; pub const SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT = "SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT"; pub const SDL_HINT_WINRT_PRIVACY_POLICY_URL = "SDL_WINRT_PRIVACY_POLICY_URL"; pub const SDL_HINT_WINRT_PRIVACY_POLICY_LABEL = "SDL_WINRT_PRIVACY_POLICY_LABEL"; pub const SDL_HINT_WINRT_HANDLE_BACK_BUTTON = "SDL_WINRT_HANDLE_BACK_BUTTON"; pub const SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES = "SDL_VIDEO_MAC_FULLSCREEN_SPACES"; pub const SDL_HINT_MAC_BACKGROUND_APP = "SDL_MAC_BACKGROUND_APP"; pub const SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION"; pub const SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION"; pub const SDL_HINT_IME_INTERNAL_EDITING = "SDL_IME_INTERNAL_EDITING"; pub const SDL_HINT_ANDROID_TRAP_BACK_BUTTON = "SDL_ANDROID_TRAP_BACK_BUTTON"; pub const SDL_HINT_ANDROID_BLOCK_ON_PAUSE = "SDL_ANDROID_BLOCK_ON_PAUSE"; pub const SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO = "SDL_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO"; pub const SDL_HINT_RETURN_KEY_HIDES_IME = "SDL_RETURN_KEY_HIDES_IME"; pub const SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT = "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT"; pub const SDL_HINT_EMSCRIPTEN_ASYNCIFY = "SDL_EMSCRIPTEN_ASYNCIFY"; pub const SDL_HINT_NO_SIGNAL_HANDLERS = "SDL_NO_SIGNAL_HANDLERS"; pub const SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 = "SDL_WINDOWS_NO_CLOSE_ON_ALT_F4"; pub const SDL_HINT_BMP_SAVE_LEGACY_FORMAT = "SDL_BMP_SAVE_LEGACY_FORMAT"; pub const SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING = "SDL_WINDOWS_DISABLE_THREAD_NAMING"; pub const SDL_HINT_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS = "SDL_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS"; pub const SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL = "SDL_WINDOWS_FORCE_SEMAPHORE_KERNEL"; pub const SDL_HINT_RPI_VIDEO_LAYER = "SDL_RPI_VIDEO_LAYER"; pub const SDL_HINT_VIDEO_DOUBLE_BUFFER = "SDL_VIDEO_DOUBLE_BUFFER"; pub const SDL_HINT_OPENGL_ES_DRIVER = "SDL_OPENGL_ES_DRIVER"; pub const SDL_HINT_AUDIO_RESAMPLING_MODE = "SDL_AUDIO_RESAMPLING_MODE"; pub const SDL_HINT_AUDIO_CATEGORY = "SDL_AUDIO_CATEGORY"; pub const SDL_HINT_RENDER_BATCHING = "SDL_RENDER_BATCHING"; pub const SDL_HINT_AUTO_UPDATE_JOYSTICKS = "SDL_AUTO_UPDATE_JOYSTICKS"; pub const SDL_HINT_AUTO_UPDATE_SENSORS = "SDL_AUTO_UPDATE_SENSORS"; pub const SDL_HINT_EVENT_LOGGING = "SDL_EVENT_LOGGING"; pub const SDL_HINT_WAVE_RIFF_CHUNK_SIZE = "SDL_WAVE_RIFF_CHUNK_SIZE"; pub const SDL_HINT_WAVE_TRUNCATION = "SDL_WAVE_TRUNCATION"; pub const SDL_HINT_WAVE_FACT_CHUNK = "SDL_WAVE_FACT_CHUNK"; pub const SDL_HINT_DISPLAY_USABLE_BOUNDS = "SDL_DISPLAY_USABLE_BOUNDS"; pub const SDL_HINT_AUDIO_DEVICE_APP_NAME = "SDL_AUDIO_DEVICE_APP_NAME"; pub const SDL_HINT_AUDIO_DEVICE_STREAM_NAME = "SDL_AUDIO_DEVICE_STREAM_NAME"; pub const SDL_HINT_PREFERRED_LOCALES = "SDL_PREFERRED_LOCALES"; pub const SDL_NONSHAPEABLE_WINDOW = -1; pub const SDL_INVALID_SHAPE_ARGUMENT = -2; pub const SDL_WINDOW_LACKS_SHAPE = -3; pub inline fn SDL_SHAPEMODEALPHA(mode: anytype) @TypeOf(((mode == ShapeModeDefault) or (mode == ShapeModeBinarizeAlpha)) or (mode == ShapeModeReverseBinarizeAlpha)) { return ((mode == ShapeModeDefault) or (mode == ShapeModeBinarizeAlpha)) or (mode == ShapeModeReverseBinarizeAlpha); } pub inline fn SDL_TICKS_PASSED(A: anytype, B: anytype) @TypeOf((@import("std").meta.cast(i32, B - A)) <= 0) { return (@import("std").meta.cast(i32, B - A)) <= 0; } pub const SDL_MAJOR_VERSION = 2; pub const SDL_PATCHLEVEL = 15; pub inline fn SDL_VERSIONNUM(X: anytype, Y: anytype, Z: anytype) @TypeOf(((X * 1000) + (Y * 100)) + Z) { return ((X * 1000) + (Y * 100)) + Z; } pub inline fn SDL_VERSION_ATLEAST(X: anytype, Y: anytype, Z: anytype) @TypeOf(SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) { return SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z); } pub const SDL_INIT_TIMER = @as(c_uint, 0x00000001); pub const SDL_INIT_AUDIO = @as(c_uint, 0x00000010); pub const SDL_INIT_VIDEO = @as(c_uint, 0x00000020); pub const SDL_INIT_JOYSTICK = @as(c_uint, 0x00000200); pub const SDL_INIT_HAPTIC = @as(c_uint, 0x00001000); pub const SDL_INIT_GAMECONTROLLER = @as(c_uint, 0x00002000); pub const SDL_INIT_EVENTS = @as(c_uint, 0x00004000); pub const SDL_INIT_SENSOR = @as(c_uint, 0x00008000); pub const SDL_INIT_NOPARACHUTE = @as(c_uint, 0x00100000); pub const SDL_INIT_EVERYTHING = ((((((SDL_INIT_TIMER | SDL_INIT_AUDIO) | SDL_INIT_VIDEO) | SDL_INIT_EVENTS) | SDL_INIT_JOYSTICK) | SDL_INIT_HAPTIC) | SDL_INIT_GAMECONTROLLER) | SDL_INIT_SENSOR; pub const SDL_semaphore = struct_SDL_semaphore; pub const SDL_BlitMap = struct_SDL_BlitMap;
src/binding/sdl.zig
pub const __builtin_bswap16 = @import("std").zig.c_builtins.__builtin_bswap16; pub const __builtin_bswap32 = @import("std").zig.c_builtins.__builtin_bswap32; pub const __builtin_bswap64 = @import("std").zig.c_builtins.__builtin_bswap64; pub const __builtin_signbit = @import("std").zig.c_builtins.__builtin_signbit; pub const __builtin_signbitf = @import("std").zig.c_builtins.__builtin_signbitf; pub const __builtin_popcount = @import("std").zig.c_builtins.__builtin_popcount; pub const __builtin_ctz = @import("std").zig.c_builtins.__builtin_ctz; pub const __builtin_clz = @import("std").zig.c_builtins.__builtin_clz; pub const __builtin_sqrt = @import("std").zig.c_builtins.__builtin_sqrt; pub const __builtin_sqrtf = @import("std").zig.c_builtins.__builtin_sqrtf; pub const __builtin_sin = @import("std").zig.c_builtins.__builtin_sin; pub const __builtin_sinf = @import("std").zig.c_builtins.__builtin_sinf; pub const __builtin_cos = @import("std").zig.c_builtins.__builtin_cos; pub const __builtin_cosf = @import("std").zig.c_builtins.__builtin_cosf; pub const __builtin_exp = @import("std").zig.c_builtins.__builtin_exp; pub const __builtin_expf = @import("std").zig.c_builtins.__builtin_expf; pub const __builtin_exp2 = @import("std").zig.c_builtins.__builtin_exp2; pub const __builtin_exp2f = @import("std").zig.c_builtins.__builtin_exp2f; pub const __builtin_log = @import("std").zig.c_builtins.__builtin_log; pub const __builtin_logf = @import("std").zig.c_builtins.__builtin_logf; pub const __builtin_log2 = @import("std").zig.c_builtins.__builtin_log2; pub const __builtin_log2f = @import("std").zig.c_builtins.__builtin_log2f; pub const __builtin_log10 = @import("std").zig.c_builtins.__builtin_log10; pub const __builtin_log10f = @import("std").zig.c_builtins.__builtin_log10f; pub const __builtin_abs = @import("std").zig.c_builtins.__builtin_abs; pub const __builtin_fabs = @import("std").zig.c_builtins.__builtin_fabs; pub const __builtin_fabsf = @import("std").zig.c_builtins.__builtin_fabsf; pub const __builtin_floor = @import("std").zig.c_builtins.__builtin_floor; pub const __builtin_floorf = @import("std").zig.c_builtins.__builtin_floorf; pub const __builtin_ceil = @import("std").zig.c_builtins.__builtin_ceil; pub const __builtin_ceilf = @import("std").zig.c_builtins.__builtin_ceilf; pub const __builtin_trunc = @import("std").zig.c_builtins.__builtin_trunc; pub const __builtin_truncf = @import("std").zig.c_builtins.__builtin_truncf; pub const __builtin_round = @import("std").zig.c_builtins.__builtin_round; pub const __builtin_roundf = @import("std").zig.c_builtins.__builtin_roundf; pub const __builtin_strlen = @import("std").zig.c_builtins.__builtin_strlen; pub const __builtin_strcmp = @import("std").zig.c_builtins.__builtin_strcmp; pub const __builtin_object_size = @import("std").zig.c_builtins.__builtin_object_size; pub const __builtin___memset_chk = @import("std").zig.c_builtins.__builtin___memset_chk; pub const __builtin_memset = @import("std").zig.c_builtins.__builtin_memset; pub const __builtin___memcpy_chk = @import("std").zig.c_builtins.__builtin___memcpy_chk; pub const __builtin_memcpy = @import("std").zig.c_builtins.__builtin_memcpy; pub const __builtin_expect = @import("std").zig.c_builtins.__builtin_expect; pub const __builtin_nanf = @import("std").zig.c_builtins.__builtin_nanf; pub const __builtin_huge_valf = @import("std").zig.c_builtins.__builtin_huge_valf; pub const __builtin_inff = @import("std").zig.c_builtins.__builtin_inff; pub const __builtin_isnan = @import("std").zig.c_builtins.__builtin_isnan; pub const __builtin_isinf = @import("std").zig.c_builtins.__builtin_isinf; pub const __builtin_isinf_sign = @import("std").zig.c_builtins.__builtin_isinf_sign; pub const __builtin_va_list = [*c]u8; pub const va_list = __builtin_va_list; pub const __gnuc_va_list = __builtin_va_list; pub const struct_Vector2 = extern struct { x: f32, y: f32, }; pub const Vector2 = struct_Vector2; pub const struct_Vector3 = extern struct { x: f32, y: f32, z: f32, }; pub const Vector3 = struct_Vector3; pub const struct_Vector4 = extern struct { x: f32, y: f32, z: f32, w: f32, }; pub const Vector4 = struct_Vector4; pub const Quaternion = Vector4; pub const struct_Matrix = extern struct { m0: f32, m4: f32, m8: f32, m12: f32, m1: f32, m5: f32, m9: f32, m13: f32, m2: f32, m6: f32, m10: f32, m14: f32, m3: f32, m7: f32, m11: f32, m15: f32, }; pub const Matrix = struct_Matrix; pub const struct_Color = extern struct { r: u8, g: u8, b: u8, a: u8, }; pub const Color = struct_Color; pub const struct_Rectangle = extern struct { x: f32, y: f32, width: f32, height: f32, }; pub const Rectangle = struct_Rectangle; pub const struct_Image = extern struct { data: ?*c_void, width: c_int, height: c_int, mipmaps: c_int, format: c_int, }; pub const Image = struct_Image; pub const struct_Texture = extern struct { id: c_uint, width: c_int, height: c_int, mipmaps: c_int, format: c_int, }; pub const Texture = struct_Texture; pub const Texture2D = Texture; pub const TextureCubemap = Texture; pub const struct_RenderTexture = extern struct { id: c_uint, texture: Texture, depth: Texture, }; pub const RenderTexture = struct_RenderTexture; pub const RenderTexture2D = RenderTexture; pub const struct_NPatchInfo = extern struct { source: Rectangle, left: c_int, top: c_int, right: c_int, bottom: c_int, layout: c_int, }; pub const NPatchInfo = struct_NPatchInfo; pub const struct_CharInfo = extern struct { value: c_int, offsetX: c_int, offsetY: c_int, advanceX: c_int, image: Image, }; pub const CharInfo = struct_CharInfo; pub const struct_Font = extern struct { baseSize: c_int, charsCount: c_int, charsPadding: c_int, texture: Texture2D, recs: [*c]Rectangle, chars: [*c]CharInfo, }; pub const Font = struct_Font; pub const struct_Camera3D = extern struct { position: Vector3, target: Vector3, up: Vector3, fovy: f32, projection: c_int, }; pub const Camera3D = struct_Camera3D; pub const Camera = Camera3D; pub const struct_Camera2D = extern struct { offset: Vector2, target: Vector2, rotation: f32, zoom: f32, }; pub const Camera2D = struct_Camera2D; pub const struct_Mesh = extern struct { vertexCount: c_int, triangleCount: c_int, vertices: [*c]f32, texcoords: [*c]f32, texcoords2: [*c]f32, normals: [*c]f32, tangents: [*c]f32, colors: [*c]u8, indices: [*c]c_ushort, animVertices: [*c]f32, animNormals: [*c]f32, boneIds: [*c]c_int, boneWeights: [*c]f32, vaoId: c_uint, vboId: [*c]c_uint, }; pub const Mesh = struct_Mesh; pub const struct_Shader = extern struct { id: c_uint, locs: [*c]c_int, }; pub const Shader = struct_Shader; pub const struct_MaterialMap = extern struct { texture: Texture2D, color: Color, value: f32, }; pub const MaterialMap = struct_MaterialMap; pub const struct_Material = extern struct { shader: Shader, maps: [*c]MaterialMap, params: [4]f32, }; pub const Material = struct_Material; pub const struct_Transform = extern struct { translation: Vector3, rotation: Quaternion, scale: Vector3, }; pub const Transform = struct_Transform; pub const struct_BoneInfo = extern struct { name: [32]u8, parent: c_int, }; pub const BoneInfo = struct_BoneInfo; pub const struct_Model = extern struct { transform: Matrix, meshCount: c_int, materialCount: c_int, meshes: [*c]Mesh, materials: [*c]Material, meshMaterial: [*c]c_int, boneCount: c_int, bones: [*c]BoneInfo, bindPose: [*c]Transform, }; pub const Model = struct_Model; pub const struct_ModelAnimation = extern struct { boneCount: c_int, frameCount: c_int, bones: [*c]BoneInfo, framePoses: [*c][*c]Transform, }; pub const ModelAnimation = struct_ModelAnimation; pub const struct_Ray = extern struct { position: Vector3, direction: Vector3, }; pub const Ray = struct_Ray; pub const struct_RayCollision = extern struct { hit: bool, distance: f32, point: Vector3, normal: Vector3, }; pub const RayCollision = struct_RayCollision; pub const struct_BoundingBox = extern struct { min: Vector3, max: Vector3, }; pub const BoundingBox = struct_BoundingBox; pub const struct_Wave = extern struct { sampleCount: c_uint, sampleRate: c_uint, sampleSize: c_uint, channels: c_uint, data: ?*c_void, }; pub const Wave = struct_Wave; pub const struct_rAudioBuffer = opaque {}; pub const rAudioBuffer = struct_rAudioBuffer; pub const struct_AudioStream = extern struct { buffer: ?*rAudioBuffer, sampleRate: c_uint, sampleSize: c_uint, channels: c_uint, }; pub const AudioStream = struct_AudioStream; pub const struct_Sound = extern struct { stream: AudioStream, sampleCount: c_uint, }; pub const Sound = struct_Sound; pub const struct_Music = extern struct { stream: AudioStream, sampleCount: c_uint, looping: bool, ctxType: c_int, ctxData: ?*c_void, }; pub const Music = struct_Music; pub const struct_VrDeviceInfo = extern struct { hResolution: c_int, vResolution: c_int, hScreenSize: f32, vScreenSize: f32, vScreenCenter: f32, eyeToScreenDistance: f32, lensSeparationDistance: f32, interpupillaryDistance: f32, lensDistortionValues: [4]f32, chromaAbCorrection: [4]f32, }; pub const VrDeviceInfo = struct_VrDeviceInfo; pub const struct_VrStereoConfig = extern struct { projection: [2]Matrix, viewOffset: [2]Matrix, leftLensCenter: [2]f32, rightLensCenter: [2]f32, leftScreenCenter: [2]f32, rightScreenCenter: [2]f32, scale: [2]f32, scaleIn: [2]f32, }; pub const VrStereoConfig = struct_VrStereoConfig; pub const FLAG_VSYNC_HINT: c_int = 64; pub const FLAG_FULLSCREEN_MODE: c_int = 2; pub const FLAG_WINDOW_RESIZABLE: c_int = 4; pub const FLAG_WINDOW_UNDECORATED: c_int = 8; pub const FLAG_WINDOW_HIDDEN: c_int = 128; pub const FLAG_WINDOW_MINIMIZED: c_int = 512; pub const FLAG_WINDOW_MAXIMIZED: c_int = 1024; pub const FLAG_WINDOW_UNFOCUSED: c_int = 2048; pub const FLAG_WINDOW_TOPMOST: c_int = 4096; pub const FLAG_WINDOW_ALWAYS_RUN: c_int = 256; pub const FLAG_WINDOW_TRANSPARENT: c_int = 16; pub const FLAG_WINDOW_HIGHDPI: c_int = 8192; pub const FLAG_MSAA_4X_HINT: c_int = 32; pub const FLAG_INTERLACED_HINT: c_int = 65536; pub const ConfigFlags = c_uint; pub const LOG_ALL: c_int = 0; pub const LOG_TRACE: c_int = 1; pub const LOG_DEBUG: c_int = 2; pub const LOG_INFO: c_int = 3; pub const LOG_WARNING: c_int = 4; pub const LOG_ERROR: c_int = 5; pub const LOG_FATAL: c_int = 6; pub const LOG_NONE: c_int = 7; pub const TraceLogLevel = c_uint; pub const KEY_NULL: c_int = 0; pub const KEY_APOSTROPHE: c_int = 39; pub const KEY_COMMA: c_int = 44; pub const KEY_MINUS: c_int = 45; pub const KEY_PERIOD: c_int = 46; pub const KEY_SLASH: c_int = 47; pub const KEY_ZERO: c_int = 48; pub const KEY_ONE: c_int = 49; pub const KEY_TWO: c_int = 50; pub const KEY_THREE: c_int = 51; pub const KEY_FOUR: c_int = 52; pub const KEY_FIVE: c_int = 53; pub const KEY_SIX: c_int = 54; pub const KEY_SEVEN: c_int = 55; pub const KEY_EIGHT: c_int = 56; pub const KEY_NINE: c_int = 57; pub const KEY_SEMICOLON: c_int = 59; pub const KEY_EQUAL: c_int = 61; pub const KEY_A: c_int = 65; pub const KEY_B: c_int = 66; pub const KEY_C: c_int = 67; pub const KEY_D: c_int = 68; pub const KEY_E: c_int = 69; pub const KEY_F: c_int = 70; pub const KEY_G: c_int = 71; pub const KEY_H: c_int = 72; pub const KEY_I: c_int = 73; pub const KEY_J: c_int = 74; pub const KEY_K: c_int = 75; pub const KEY_L: c_int = 76; pub const KEY_M: c_int = 77; pub const KEY_N: c_int = 78; pub const KEY_O: c_int = 79; pub const KEY_P: c_int = 80; pub const KEY_Q: c_int = 81; pub const KEY_R: c_int = 82; pub const KEY_S: c_int = 83; pub const KEY_T: c_int = 84; pub const KEY_U: c_int = 85; pub const KEY_V: c_int = 86; pub const KEY_W: c_int = 87; pub const KEY_X: c_int = 88; pub const KEY_Y: c_int = 89; pub const KEY_Z: c_int = 90; pub const KEY_LEFT_BRACKET: c_int = 91; pub const KEY_BACKSLASH: c_int = 92; pub const KEY_RIGHT_BRACKET: c_int = 93; pub const KEY_GRAVE: c_int = 96; pub const KEY_SPACE: c_int = 32; pub const KEY_ESCAPE: c_int = 256; pub const KEY_ENTER: c_int = 257; pub const KEY_TAB: c_int = 258; pub const KEY_BACKSPACE: c_int = 259; pub const KEY_INSERT: c_int = 260; pub const KEY_DELETE: c_int = 261; pub const KEY_RIGHT: c_int = 262; pub const KEY_LEFT: c_int = 263; pub const KEY_DOWN: c_int = 264; pub const KEY_UP: c_int = 265; pub const KEY_PAGE_UP: c_int = 266; pub const KEY_PAGE_DOWN: c_int = 267; pub const KEY_HOME: c_int = 268; pub const KEY_END: c_int = 269; pub const KEY_CAPS_LOCK: c_int = 280; pub const KEY_SCROLL_LOCK: c_int = 281; pub const KEY_NUM_LOCK: c_int = 282; pub const KEY_PRINT_SCREEN: c_int = 283; pub const KEY_PAUSE: c_int = 284; pub const KEY_F1: c_int = 290; pub const KEY_F2: c_int = 291; pub const KEY_F3: c_int = 292; pub const KEY_F4: c_int = 293; pub const KEY_F5: c_int = 294; pub const KEY_F6: c_int = 295; pub const KEY_F7: c_int = 296; pub const KEY_F8: c_int = 297; pub const KEY_F9: c_int = 298; pub const KEY_F10: c_int = 299; pub const KEY_F11: c_int = 300; pub const KEY_F12: c_int = 301; pub const KEY_LEFT_SHIFT: c_int = 340; pub const KEY_LEFT_CONTROL: c_int = 341; pub const KEY_LEFT_ALT: c_int = 342; pub const KEY_LEFT_SUPER: c_int = 343; pub const KEY_RIGHT_SHIFT: c_int = 344; pub const KEY_RIGHT_CONTROL: c_int = 345; pub const KEY_RIGHT_ALT: c_int = 346; pub const KEY_RIGHT_SUPER: c_int = 347; pub const KEY_KB_MENU: c_int = 348; pub const KEY_KP_0: c_int = 320; pub const KEY_KP_1: c_int = 321; pub const KEY_KP_2: c_int = 322; pub const KEY_KP_3: c_int = 323; pub const KEY_KP_4: c_int = 324; pub const KEY_KP_5: c_int = 325; pub const KEY_KP_6: c_int = 326; pub const KEY_KP_7: c_int = 327; pub const KEY_KP_8: c_int = 328; pub const KEY_KP_9: c_int = 329; pub const KEY_KP_DECIMAL: c_int = 330; pub const KEY_KP_DIVIDE: c_int = 331; pub const KEY_KP_MULTIPLY: c_int = 332; pub const KEY_KP_SUBTRACT: c_int = 333; pub const KEY_KP_ADD: c_int = 334; pub const KEY_KP_ENTER: c_int = 335; pub const KEY_KP_EQUAL: c_int = 336; pub const KEY_BACK: c_int = 4; pub const KEY_MENU: c_int = 82; pub const KEY_VOLUME_UP: c_int = 24; pub const KEY_VOLUME_DOWN: c_int = 25; pub const KeyboardKey = c_uint; pub const MOUSE_BUTTON_LEFT: c_int = 0; pub const MOUSE_BUTTON_RIGHT: c_int = 1; pub const MOUSE_BUTTON_MIDDLE: c_int = 2; pub const MOUSE_BUTTON_SIDE: c_int = 3; pub const MOUSE_BUTTON_EXTRA: c_int = 4; pub const MOUSE_BUTTON_FORWARD: c_int = 5; pub const MOUSE_BUTTON_BACK: c_int = 6; pub const MouseButton = c_uint; pub const MOUSE_CURSOR_DEFAULT: c_int = 0; pub const MOUSE_CURSOR_ARROW: c_int = 1; pub const MOUSE_CURSOR_IBEAM: c_int = 2; pub const MOUSE_CURSOR_CROSSHAIR: c_int = 3; pub const MOUSE_CURSOR_POINTING_HAND: c_int = 4; pub const MOUSE_CURSOR_RESIZE_EW: c_int = 5; pub const MOUSE_CURSOR_RESIZE_NS: c_int = 6; pub const MOUSE_CURSOR_RESIZE_NWSE: c_int = 7; pub const MOUSE_CURSOR_RESIZE_NESW: c_int = 8; pub const MOUSE_CURSOR_RESIZE_ALL: c_int = 9; pub const MOUSE_CURSOR_NOT_ALLOWED: c_int = 10; pub const MouseCursor = c_uint; pub const GAMEPAD_BUTTON_UNKNOWN: c_int = 0; pub const GAMEPAD_BUTTON_LEFT_FACE_UP: c_int = 1; pub const GAMEPAD_BUTTON_LEFT_FACE_RIGHT: c_int = 2; pub const GAMEPAD_BUTTON_LEFT_FACE_DOWN: c_int = 3; pub const GAMEPAD_BUTTON_LEFT_FACE_LEFT: c_int = 4; pub const GAMEPAD_BUTTON_RIGHT_FACE_UP: c_int = 5; pub const GAMEPAD_BUTTON_RIGHT_FACE_RIGHT: c_int = 6; pub const GAMEPAD_BUTTON_RIGHT_FACE_DOWN: c_int = 7; pub const GAMEPAD_BUTTON_RIGHT_FACE_LEFT: c_int = 8; pub const GAMEPAD_BUTTON_LEFT_TRIGGER_1: c_int = 9; pub const GAMEPAD_BUTTON_LEFT_TRIGGER_2: c_int = 10; pub const GAMEPAD_BUTTON_RIGHT_TRIGGER_1: c_int = 11; pub const GAMEPAD_BUTTON_RIGHT_TRIGGER_2: c_int = 12; pub const GAMEPAD_BUTTON_MIDDLE_LEFT: c_int = 13; pub const GAMEPAD_BUTTON_MIDDLE: c_int = 14; pub const GAMEPAD_BUTTON_MIDDLE_RIGHT: c_int = 15; pub const GAMEPAD_BUTTON_LEFT_THUMB: c_int = 16; pub const GAMEPAD_BUTTON_RIGHT_THUMB: c_int = 17; pub const GamepadButton = c_uint; pub const GAMEPAD_AXIS_LEFT_X: c_int = 0; pub const GAMEPAD_AXIS_LEFT_Y: c_int = 1; pub const GAMEPAD_AXIS_RIGHT_X: c_int = 2; pub const GAMEPAD_AXIS_RIGHT_Y: c_int = 3; pub const GAMEPAD_AXIS_LEFT_TRIGGER: c_int = 4; pub const GAMEPAD_AXIS_RIGHT_TRIGGER: c_int = 5; pub const GamepadAxis = c_uint; pub const MATERIAL_MAP_ALBEDO: c_int = 0; pub const MATERIAL_MAP_METALNESS: c_int = 1; pub const MATERIAL_MAP_NORMAL: c_int = 2; pub const MATERIAL_MAP_ROUGHNESS: c_int = 3; pub const MATERIAL_MAP_OCCLUSION: c_int = 4; pub const MATERIAL_MAP_EMISSION: c_int = 5; pub const MATERIAL_MAP_HEIGHT: c_int = 6; pub const MATERIAL_MAP_CUBEMAP: c_int = 7; pub const MATERIAL_MAP_IRRADIANCE: c_int = 8; pub const MATERIAL_MAP_PREFILTER: c_int = 9; pub const MATERIAL_MAP_BRDG: c_int = 10; pub const MaterialMapIndex = c_uint; pub const SHADER_LOC_VERTEX_POSITION: c_int = 0; pub const SHADER_LOC_VERTEX_TEXCOORD01: c_int = 1; pub const SHADER_LOC_VERTEX_TEXCOORD02: c_int = 2; pub const SHADER_LOC_VERTEX_NORMAL: c_int = 3; pub const SHADER_LOC_VERTEX_TANGENT: c_int = 4; pub const SHADER_LOC_VERTEX_COLOR: c_int = 5; pub const SHADER_LOC_MATRIX_MVP: c_int = 6; pub const SHADER_LOC_MATRIX_VIEW: c_int = 7; pub const SHADER_LOC_MATRIX_PROJECTION: c_int = 8; pub const SHADER_LOC_MATRIX_MODEL: c_int = 9; pub const SHADER_LOC_MATRIX_NORMAL: c_int = 10; pub const SHADER_LOC_VECTOR_VIEW: c_int = 11; pub const SHADER_LOC_COLOR_DIFFUSE: c_int = 12; pub const SHADER_LOC_COLOR_SPECULAR: c_int = 13; pub const SHADER_LOC_COLOR_AMBIENT: c_int = 14; pub const SHADER_LOC_MAP_ALBEDO: c_int = 15; pub const SHADER_LOC_MAP_METALNESS: c_int = 16; pub const SHADER_LOC_MAP_NORMAL: c_int = 17; pub const SHADER_LOC_MAP_ROUGHNESS: c_int = 18; pub const SHADER_LOC_MAP_OCCLUSION: c_int = 19; pub const SHADER_LOC_MAP_EMISSION: c_int = 20; pub const SHADER_LOC_MAP_HEIGHT: c_int = 21; pub const SHADER_LOC_MAP_CUBEMAP: c_int = 22; pub const SHADER_LOC_MAP_IRRADIANCE: c_int = 23; pub const SHADER_LOC_MAP_PREFILTER: c_int = 24; pub const SHADER_LOC_MAP_BRDF: c_int = 25; pub const ShaderLocationIndex = c_uint; pub const SHADER_UNIFORM_FLOAT: c_int = 0; pub const SHADER_UNIFORM_VEC2: c_int = 1; pub const SHADER_UNIFORM_VEC3: c_int = 2; pub const SHADER_UNIFORM_VEC4: c_int = 3; pub const SHADER_UNIFORM_INT: c_int = 4; pub const SHADER_UNIFORM_IVEC2: c_int = 5; pub const SHADER_UNIFORM_IVEC3: c_int = 6; pub const SHADER_UNIFORM_IVEC4: c_int = 7; pub const SHADER_UNIFORM_SAMPLER2D: c_int = 8; pub const ShaderUniformDataType = c_uint; pub const SHADER_ATTRIB_FLOAT: c_int = 0; pub const SHADER_ATTRIB_VEC2: c_int = 1; pub const SHADER_ATTRIB_VEC3: c_int = 2; pub const SHADER_ATTRIB_VEC4: c_int = 3; pub const ShaderAttributeDataType = c_uint; pub const PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: c_int = 1; pub const PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: c_int = 2; pub const PIXELFORMAT_UNCOMPRESSED_R5G6B5: c_int = 3; pub const PIXELFORMAT_UNCOMPRESSED_R8G8B8: c_int = 4; pub const PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: c_int = 5; pub const PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: c_int = 6; pub const PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: c_int = 7; pub const PIXELFORMAT_UNCOMPRESSED_R32: c_int = 8; pub const PIXELFORMAT_UNCOMPRESSED_R32G32B32: c_int = 9; pub const PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: c_int = 10; pub const PIXELFORMAT_COMPRESSED_DXT1_RGB: c_int = 11; pub const PIXELFORMAT_COMPRESSED_DXT1_RGBA: c_int = 12; pub const PIXELFORMAT_COMPRESSED_DXT3_RGBA: c_int = 13; pub const PIXELFORMAT_COMPRESSED_DXT5_RGBA: c_int = 14; pub const PIXELFORMAT_COMPRESSED_ETC1_RGB: c_int = 15; pub const PIXELFORMAT_COMPRESSED_ETC2_RGB: c_int = 16; pub const PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: c_int = 17; pub const PIXELFORMAT_COMPRESSED_PVRT_RGB: c_int = 18; pub const PIXELFORMAT_COMPRESSED_PVRT_RGBA: c_int = 19; pub const PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: c_int = 20; pub const PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: c_int = 21; pub const PixelFormat = c_uint; pub const TEXTURE_FILTER_POINT: c_int = 0; pub const TEXTURE_FILTER_BILINEAR: c_int = 1; pub const TEXTURE_FILTER_TRILINEAR: c_int = 2; pub const TEXTURE_FILTER_ANISOTROPIC_4X: c_int = 3; pub const TEXTURE_FILTER_ANISOTROPIC_8X: c_int = 4; pub const TEXTURE_FILTER_ANISOTROPIC_16X: c_int = 5; pub const TextureFilter = c_uint; pub const TEXTURE_WRAP_REPEAT: c_int = 0; pub const TEXTURE_WRAP_CLAMP: c_int = 1; pub const TEXTURE_WRAP_MIRROR_REPEAT: c_int = 2; pub const TEXTURE_WRAP_MIRROR_CLAMP: c_int = 3; pub const TextureWrap = c_uint; pub const CUBEMAP_LAYOUT_AUTO_DETECT: c_int = 0; pub const CUBEMAP_LAYOUT_LINE_VERTICAL: c_int = 1; pub const CUBEMAP_LAYOUT_LINE_HORIZONTAL: c_int = 2; pub const CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR: c_int = 3; pub const CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE: c_int = 4; pub const CUBEMAP_LAYOUT_PANORAMA: c_int = 5; pub const CubemapLayout = c_uint; pub const FONT_DEFAULT: c_int = 0; pub const FONT_BITMAP: c_int = 1; pub const FONT_SDF: c_int = 2; pub const FontType = c_uint; pub const BLEND_ALPHA: c_int = 0; pub const BLEND_ADDITIVE: c_int = 1; pub const BLEND_MULTIPLIED: c_int = 2; pub const BLEND_ADD_COLORS: c_int = 3; pub const BLEND_SUBTRACT_COLORS: c_int = 4; pub const BLEND_CUSTOM: c_int = 5; pub const BlendMode = c_uint; pub const GESTURE_NONE: c_int = 0; pub const GESTURE_TAP: c_int = 1; pub const GESTURE_DOUBLETAP: c_int = 2; pub const GESTURE_HOLD: c_int = 4; pub const GESTURE_DRAG: c_int = 8; pub const GESTURE_SWIPE_RIGHT: c_int = 16; pub const GESTURE_SWIPE_LEFT: c_int = 32; pub const GESTURE_SWIPE_UP: c_int = 64; pub const GESTURE_SWIPE_DOWN: c_int = 128; pub const GESTURE_PINCH_IN: c_int = 256; pub const GESTURE_PINCH_OUT: c_int = 512; pub const Gesture = c_uint; pub const CAMERA_CUSTOM: c_int = 0; pub const CAMERA_FREE: c_int = 1; pub const CAMERA_ORBITAL: c_int = 2; pub const CAMERA_FIRST_PERSON: c_int = 3; pub const CAMERA_THIRD_PERSON: c_int = 4; pub const CameraMode = c_uint; pub const CAMERA_PERSPECTIVE: c_int = 0; pub const CAMERA_ORTHOGRAPHIC: c_int = 1; pub const CameraProjection = c_uint; pub const NPATCH_NINE_PATCH: c_int = 0; pub const NPATCH_THREE_PATCH_VERTICAL: c_int = 1; pub const NPATCH_THREE_PATCH_HORIZONTAL: c_int = 2; pub const NPatchLayout = c_uint; pub const TraceLogCallback = ?fn (c_int, [*c]const u8, va_list) callconv(.C) void; pub const LoadFileDataCallback = ?fn ([*c]const u8, [*c]c_uint) callconv(.C) [*c]u8; pub const SaveFileDataCallback = ?fn ([*c]const u8, ?*c_void, c_uint) callconv(.C) bool; pub const LoadFileTextCallback = ?fn ([*c]const u8) callconv(.C) [*c]u8; pub const SaveFileTextCallback = ?fn ([*c]const u8, [*c]u8) callconv(.C) bool; pub extern fn InitWindow(width: c_int, height: c_int, title: [*c]const u8) void; pub extern fn WindowShouldClose() bool; pub extern fn CloseWindow() void; pub extern fn IsWindowReady() bool; pub extern fn IsWindowFullscreen() bool; pub extern fn IsWindowHidden() bool; pub extern fn IsWindowMinimized() bool; pub extern fn IsWindowMaximized() bool; pub extern fn IsWindowFocused() bool; pub extern fn IsWindowResized() bool; pub extern fn IsWindowState(flag: c_uint) bool; pub extern fn SetWindowState(flags: c_uint) void; pub extern fn ClearWindowState(flags: c_uint) void; pub extern fn ToggleFullscreen() void; pub extern fn MaximizeWindow() void; pub extern fn MinimizeWindow() void; pub extern fn RestoreWindow() void; pub extern fn SetWindowIcon(image: Image) void; pub extern fn SetWindowTitle(title: [*c]const u8) void; pub extern fn SetWindowPosition(x: c_int, y: c_int) void; pub extern fn SetWindowMonitor(monitor: c_int) void; pub extern fn SetWindowMinSize(width: c_int, height: c_int) void; pub extern fn SetWindowSize(width: c_int, height: c_int) void; pub extern fn GetWindowHandle() ?*c_void; pub extern fn GetScreenWidth() c_int; pub extern fn GetScreenHeight() c_int; pub extern fn GetMonitorCount() c_int; pub extern fn GetCurrentMonitor() c_int; pub extern fn GetMonitorPosition(monitor: c_int) Vector2; pub extern fn GetMonitorWidth(monitor: c_int) c_int; pub extern fn GetMonitorHeight(monitor: c_int) c_int; pub extern fn GetMonitorPhysicalWidth(monitor: c_int) c_int; pub extern fn GetMonitorPhysicalHeight(monitor: c_int) c_int; pub extern fn GetMonitorRefreshRate(monitor: c_int) c_int; pub extern fn GetWindowPosition() Vector2; pub extern fn GetWindowScaleDPI() Vector2; pub extern fn GetMonitorName(monitor: c_int) [*c]const u8; pub extern fn SetClipboardText(text: [*c]const u8) void; pub extern fn GetClipboardText() [*c]const u8; pub extern fn SwapScreenBuffer() void; pub extern fn PollInputEvents() void; pub extern fn WaitTime(ms: f32) void; pub extern fn ShowCursor() void; pub extern fn HideCursor() void; pub extern fn IsCursorHidden() bool; pub extern fn EnableCursor() void; pub extern fn DisableCursor() void; pub extern fn IsCursorOnScreen() bool; pub extern fn ClearBackground(color: Color) void; pub extern fn BeginDrawing() void; pub extern fn EndDrawing() void; pub extern fn BeginMode2D(camera: Camera2D) void; pub extern fn EndMode2D() void; pub extern fn BeginMode3D(camera: Camera3D) void; pub extern fn EndMode3D() void; pub extern fn BeginTextureMode(target: RenderTexture2D) void; pub extern fn EndTextureMode() void; pub extern fn BeginShaderMode(shader: Shader) void; pub extern fn EndShaderMode() void; pub extern fn BeginBlendMode(mode: c_int) void; pub extern fn EndBlendMode() void; pub extern fn BeginScissorMode(x: c_int, y: c_int, width: c_int, height: c_int) void; pub extern fn EndScissorMode() void; pub extern fn BeginVrStereoMode(config: VrStereoConfig) void; pub extern fn EndVrStereoMode() void; pub extern fn LoadVrStereoConfig(device: VrDeviceInfo) VrStereoConfig; pub extern fn UnloadVrStereoConfig(config: VrStereoConfig) void; pub extern fn LoadShader(vsFileName: [*c]const u8, fsFileName: [*c]const u8) Shader; pub extern fn LoadShaderFromMemory(vsCode: [*c]const u8, fsCode: [*c]const u8) Shader; pub extern fn GetShaderLocation(shader: Shader, uniformName: [*c]const u8) c_int; pub extern fn GetShaderLocationAttrib(shader: Shader, attribName: [*c]const u8) c_int; pub extern fn SetShaderValue(shader: Shader, locIndex: c_int, value: ?*const c_void, uniformType: c_int) void; pub extern fn SetShaderValueV(shader: Shader, locIndex: c_int, value: ?*const c_void, uniformType: c_int, count: c_int) void; pub extern fn SetShaderValueMatrix(shader: Shader, locIndex: c_int, mat: Matrix) void; pub extern fn SetShaderValueTexture(shader: Shader, locIndex: c_int, texture: Texture2D) void; pub extern fn UnloadShader(shader: Shader) void; pub extern fn GetMouseRay(mousePosition: Vector2, camera: Camera) Ray; pub extern fn GetCameraMatrix(camera: Camera) Matrix; pub extern fn GetCameraMatrix2D(camera: Camera2D) Matrix; pub extern fn GetWorldToScreen(position: Vector3, camera: Camera) Vector2; pub extern fn GetWorldToScreenEx(position: Vector3, camera: Camera, width: c_int, height: c_int) Vector2; pub extern fn GetWorldToScreen2D(position: Vector2, camera: Camera2D) Vector2; pub extern fn GetScreenToWorld2D(position: Vector2, camera: Camera2D) Vector2; pub extern fn SetTargetFPS(fps: c_int) void; pub extern fn GetFPS() c_int; pub extern fn GetFrameTime() f32; pub extern fn GetTime() f64; pub extern fn GetRandomValue(min: c_int, max: c_int) c_int; pub extern fn TakeScreenshot(fileName: [*c]const u8) void; pub extern fn SetConfigFlags(flags: c_uint) void; pub extern fn TraceLog(logLevel: c_int, text: [*c]const u8, ...) void; pub extern fn SetTraceLogLevel(logLevel: c_int) void; pub extern fn MemAlloc(size: c_int) ?*c_void; pub extern fn MemRealloc(ptr: ?*c_void, size: c_int) ?*c_void; pub extern fn MemFree(ptr: ?*c_void) void; pub extern fn SetTraceLogCallback(callback: TraceLogCallback) void; pub extern fn SetLoadFileDataCallback(callback: LoadFileDataCallback) void; pub extern fn SetSaveFileDataCallback(callback: SaveFileDataCallback) void; pub extern fn SetLoadFileTextCallback(callback: LoadFileTextCallback) void; pub extern fn SetSaveFileTextCallback(callback: SaveFileTextCallback) void; pub extern fn LoadFileData(fileName: [*c]const u8, bytesRead: [*c]c_uint) [*c]u8; pub extern fn UnloadFileData(data: [*c]u8) void; pub extern fn SaveFileData(fileName: [*c]const u8, data: ?*c_void, bytesToWrite: c_uint) bool; pub extern fn LoadFileText(fileName: [*c]const u8) [*c]u8; pub extern fn UnloadFileText(text: [*c]u8) void; pub extern fn SaveFileText(fileName: [*c]const u8, text: [*c]u8) bool; pub extern fn FileExists(fileName: [*c]const u8) bool; pub extern fn DirectoryExists(dirPath: [*c]const u8) bool; pub extern fn IsFileExtension(fileName: [*c]const u8, ext: [*c]const u8) bool; pub extern fn GetFileExtension(fileName: [*c]const u8) [*c]const u8; pub extern fn GetFileName(filePath: [*c]const u8) [*c]const u8; pub extern fn GetFileNameWithoutExt(filePath: [*c]const u8) [*c]const u8; pub extern fn GetDirectoryPath(filePath: [*c]const u8) [*c]const u8; pub extern fn GetPrevDirectoryPath(dirPath: [*c]const u8) [*c]const u8; pub extern fn GetWorkingDirectory() [*c]const u8; pub extern fn GetDirectoryFiles(dirPath: [*c]const u8, count: [*c]c_int) [*c][*c]u8; pub extern fn ClearDirectoryFiles() void; pub extern fn ChangeDirectory(dir: [*c]const u8) bool; pub extern fn IsFileDropped() bool; pub extern fn GetDroppedFiles(count: [*c]c_int) [*c][*c]u8; pub extern fn ClearDroppedFiles() void; pub extern fn GetFileModTime(fileName: [*c]const u8) c_long; pub extern fn CompressData(data: [*c]u8, dataLength: c_int, compDataLength: [*c]c_int) [*c]u8; pub extern fn DecompressData(compData: [*c]u8, compDataLength: c_int, dataLength: [*c]c_int) [*c]u8; pub extern fn SaveStorageValue(position: c_uint, value: c_int) bool; pub extern fn LoadStorageValue(position: c_uint) c_int; pub extern fn OpenURL(url: [*c]const u8) void; pub extern fn IsKeyPressed(key: c_int) bool; pub extern fn IsKeyDown(key: c_int) bool; pub extern fn IsKeyReleased(key: c_int) bool; pub extern fn IsKeyUp(key: c_int) bool; pub extern fn SetExitKey(key: c_int) void; pub extern fn GetKeyPressed() c_int; pub extern fn GetCharPressed() c_int; pub extern fn IsGamepadAvailable(gamepad: c_int) bool; pub extern fn IsGamepadName(gamepad: c_int, name: [*c]const u8) bool; pub extern fn GetGamepadName(gamepad: c_int) [*c]const u8; pub extern fn IsGamepadButtonPressed(gamepad: c_int, button: c_int) bool; pub extern fn IsGamepadButtonDown(gamepad: c_int, button: c_int) bool; pub extern fn IsGamepadButtonReleased(gamepad: c_int, button: c_int) bool; pub extern fn IsGamepadButtonUp(gamepad: c_int, button: c_int) bool; pub extern fn GetGamepadButtonPressed() c_int; pub extern fn GetGamepadAxisCount(gamepad: c_int) c_int; pub extern fn GetGamepadAxisMovement(gamepad: c_int, axis: c_int) f32; pub extern fn SetGamepadMappings(mappings: [*c]const u8) c_int; pub extern fn IsMouseButtonPressed(button: c_int) bool; pub extern fn IsMouseButtonDown(button: c_int) bool; pub extern fn IsMouseButtonReleased(button: c_int) bool; pub extern fn IsMouseButtonUp(button: c_int) bool; pub extern fn GetMouseX() c_int; pub extern fn GetMouseY() c_int; pub extern fn GetMousePosition() Vector2; pub extern fn GetMouseDelta() Vector2; pub extern fn SetMousePosition(x: c_int, y: c_int) void; pub extern fn SetMouseOffset(offsetX: c_int, offsetY: c_int) void; pub extern fn SetMouseScale(scaleX: f32, scaleY: f32) void; pub extern fn GetMouseWheelMove() f32; pub extern fn SetMouseCursor(cursor: c_int) void; pub extern fn GetTouchX() c_int; pub extern fn GetTouchY() c_int; pub extern fn GetTouchPosition(index: c_int) Vector2; pub extern fn SetGesturesEnabled(flags: c_uint) void; pub extern fn IsGestureDetected(gesture: c_int) bool; pub extern fn GetGestureDetected() c_int; pub extern fn GetTouchPointsCount() c_int; pub extern fn GetGestureHoldDuration() f32; pub extern fn GetGestureDragVector() Vector2; pub extern fn GetGestureDragAngle() f32; pub extern fn GetGesturePinchVector() Vector2; pub extern fn GetGesturePinchAngle() f32; pub extern fn SetCameraMode(camera: Camera, mode: c_int) void; pub extern fn UpdateCamera(camera: [*c]Camera) void; pub extern fn SetCameraPanControl(keyPan: c_int) void; pub extern fn SetCameraAltControl(keyAlt: c_int) void; pub extern fn SetCameraSmoothZoomControl(keySmoothZoom: c_int) void; pub extern fn SetCameraMoveControls(keyFront: c_int, keyBack: c_int, keyRight: c_int, keyLeft: c_int, keyUp: c_int, keyDown: c_int) void; pub extern fn SetShapesTexture(texture: Texture2D, source: Rectangle) void; pub extern fn DrawPixel(posX: c_int, posY: c_int, color: Color) void; pub extern fn DrawPixelV(position: Vector2, color: Color) void; pub extern fn DrawLine(startPosX: c_int, startPosY: c_int, endPosX: c_int, endPosY: c_int, color: Color) void; pub extern fn DrawLineV(startPos: Vector2, endPos: Vector2, color: Color) void; pub extern fn DrawLineEx(startPos: Vector2, endPos: Vector2, thick: f32, color: Color) void; pub extern fn DrawLineBezier(startPos: Vector2, endPos: Vector2, thick: f32, color: Color) void; pub extern fn DrawLineBezierQuad(startPos: Vector2, endPos: Vector2, controlPos: Vector2, thick: f32, color: Color) void; pub extern fn DrawLineStrip(points: [*c]Vector2, pointsCount: c_int, color: Color) void; pub extern fn DrawCircle(centerX: c_int, centerY: c_int, radius: f32, color: Color) void; pub extern fn DrawCircleSector(center: Vector2, radius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawCircleSectorLines(center: Vector2, radius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawCircleGradient(centerX: c_int, centerY: c_int, radius: f32, color1: Color, color2: Color) void; pub extern fn DrawCircleV(center: Vector2, radius: f32, color: Color) void; pub extern fn DrawCircleLines(centerX: c_int, centerY: c_int, radius: f32, color: Color) void; pub extern fn DrawEllipse(centerX: c_int, centerY: c_int, radiusH: f32, radiusV: f32, color: Color) void; pub extern fn DrawEllipseLines(centerX: c_int, centerY: c_int, radiusH: f32, radiusV: f32, color: Color) void; pub extern fn DrawRing(center: Vector2, innerRadius: f32, outerRadius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawRingLines(center: Vector2, innerRadius: f32, outerRadius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawRectangle(posX: c_int, posY: c_int, width: c_int, height: c_int, color: Color) void; pub extern fn DrawRectangleV(position: Vector2, size: Vector2, color: Color) void; pub extern fn DrawRectangleRec(rec: Rectangle, color: Color) void; pub extern fn DrawRectanglePro(rec: Rectangle, origin: Vector2, rotation: f32, color: Color) void; pub extern fn DrawRectangleGradientV(posX: c_int, posY: c_int, width: c_int, height: c_int, color1: Color, color2: Color) void; pub extern fn DrawRectangleGradientH(posX: c_int, posY: c_int, width: c_int, height: c_int, color1: Color, color2: Color) void; pub extern fn DrawRectangleGradientEx(rec: Rectangle, col1: Color, col2: Color, col3: Color, col4: Color) void; pub extern fn DrawRectangleLines(posX: c_int, posY: c_int, width: c_int, height: c_int, color: Color) void; pub extern fn DrawRectangleLinesEx(rec: Rectangle, lineThick: f32, color: Color) void; pub extern fn DrawRectangleRounded(rec: Rectangle, roundness: f32, segments: c_int, color: Color) void; pub extern fn DrawRectangleRoundedLines(rec: Rectangle, roundness: f32, segments: c_int, lineThick: f32, color: Color) void; pub extern fn DrawTriangle(v1: Vector2, v2: Vector2, v3: Vector2, color: Color) void; pub extern fn DrawTriangleLines(v1: Vector2, v2: Vector2, v3: Vector2, color: Color) void; pub extern fn DrawTriangleFan(points: [*c]Vector2, pointsCount: c_int, color: Color) void; pub extern fn DrawTriangleStrip(points: [*c]Vector2, pointsCount: c_int, color: Color) void; pub extern fn DrawPoly(center: Vector2, sides: c_int, radius: f32, rotation: f32, color: Color) void; pub extern fn DrawPolyLines(center: Vector2, sides: c_int, radius: f32, rotation: f32, color: Color) void; pub extern fn DrawPolyLinesEx(center: Vector2, sides: c_int, radius: f32, rotation: f32, lineThick: f32, color: Color) void; pub extern fn CheckCollisionRecs(rec1: Rectangle, rec2: Rectangle) bool; pub extern fn CheckCollisionCircles(center1: Vector2, radius1: f32, center2: Vector2, radius2: f32) bool; pub extern fn CheckCollisionCircleRec(center: Vector2, radius: f32, rec: Rectangle) bool; pub extern fn CheckCollisionPointRec(point: Vector2, rec: Rectangle) bool; pub extern fn CheckCollisionPointCircle(point: Vector2, center: Vector2, radius: f32) bool; pub extern fn CheckCollisionPointTriangle(point: Vector2, p1: Vector2, p2: Vector2, p3: Vector2) bool; pub extern fn CheckCollisionLines(startPos1: Vector2, endPos1: Vector2, startPos2: Vector2, endPos2: Vector2, collisionPoint: [*c]Vector2) bool; pub extern fn GetCollisionRec(rec1: Rectangle, rec2: Rectangle) Rectangle; pub extern fn LoadImage(fileName: [*c]const u8) Image; pub extern fn LoadImageRaw(fileName: [*c]const u8, width: c_int, height: c_int, format: c_int, headerSize: c_int) Image; pub extern fn LoadImageAnim(fileName: [*c]const u8, frames: [*c]c_int) Image; pub extern fn LoadImageFromMemory(fileType: [*c]const u8, fileData: [*c]const u8, dataSize: c_int) Image; pub extern fn LoadImageFromTexture(texture: Texture2D) Image; pub extern fn LoadImageFromScreen() Image; pub extern fn UnloadImage(image: Image) void; pub extern fn ExportImage(image: Image, fileName: [*c]const u8) bool; pub extern fn ExportImageAsCode(image: Image, fileName: [*c]const u8) bool; pub extern fn GenImageColor(width: c_int, height: c_int, color: Color) Image; pub extern fn GenImageGradientV(width: c_int, height: c_int, top: Color, bottom: Color) Image; pub extern fn GenImageGradientH(width: c_int, height: c_int, left: Color, right: Color) Image; pub extern fn GenImageGradientRadial(width: c_int, height: c_int, density: f32, inner: Color, outer: Color) Image; pub extern fn GenImageChecked(width: c_int, height: c_int, checksX: c_int, checksY: c_int, col1: Color, col2: Color) Image; pub extern fn GenImageWhiteNoise(width: c_int, height: c_int, factor: f32) Image; pub extern fn GenImagePerlinNoise(width: c_int, height: c_int, offsetX: c_int, offsetY: c_int, scale: f32) Image; pub extern fn GenImageCellular(width: c_int, height: c_int, tileSize: c_int) Image; pub extern fn ImageCopy(image: Image) Image; pub extern fn ImageFromImage(image: Image, rec: Rectangle) Image; pub extern fn ImageText(text: [*c]const u8, fontSize: c_int, color: Color) Image; pub extern fn ImageTextEx(font: Font, text: [*c]const u8, fontSize: f32, spacing: f32, tint: Color) Image; pub extern fn ImageFormat(image: [*c]Image, newFormat: c_int) void; pub extern fn ImageToPOT(image: [*c]Image, fill: Color) void; pub extern fn ImageCrop(image: [*c]Image, crop: Rectangle) void; pub extern fn ImageAlphaCrop(image: [*c]Image, threshold: f32) void; pub extern fn ImageAlphaClear(image: [*c]Image, color: Color, threshold: f32) void; pub extern fn ImageAlphaMask(image: [*c]Image, alphaMask: Image) void; pub extern fn ImageAlphaPremultiply(image: [*c]Image) void; pub extern fn ImageResize(image: [*c]Image, newWidth: c_int, newHeight: c_int) void; pub extern fn ImageResizeNN(image: [*c]Image, newWidth: c_int, newHeight: c_int) void; pub extern fn ImageResizeCanvas(image: [*c]Image, newWidth: c_int, newHeight: c_int, offsetX: c_int, offsetY: c_int, fill: Color) void; pub extern fn ImageMipmaps(image: [*c]Image) void; pub extern fn ImageDither(image: [*c]Image, rBpp: c_int, gBpp: c_int, bBpp: c_int, aBpp: c_int) void; pub extern fn ImageFlipVertical(image: [*c]Image) void; pub extern fn ImageFlipHorizontal(image: [*c]Image) void; pub extern fn ImageRotateCW(image: [*c]Image) void; pub extern fn ImageRotateCCW(image: [*c]Image) void; pub extern fn ImageColorTint(image: [*c]Image, color: Color) void; pub extern fn ImageColorInvert(image: [*c]Image) void; pub extern fn ImageColorGrayscale(image: [*c]Image) void; pub extern fn ImageColorContrast(image: [*c]Image, contrast: f32) void; pub extern fn ImageColorBrightness(image: [*c]Image, brightness: c_int) void; pub extern fn ImageColorReplace(image: [*c]Image, color: Color, replace: Color) void; pub extern fn LoadImageColors(image: Image) [*c]Color; pub extern fn LoadImagePalette(image: Image, maxPaletteSize: c_int, colorsCount: [*c]c_int) [*c]Color; pub extern fn UnloadImageColors(colors: [*c]Color) void; pub extern fn UnloadImagePalette(colors: [*c]Color) void; pub extern fn GetImageAlphaBorder(image: Image, threshold: f32) Rectangle; pub extern fn ImageClearBackground(dst: [*c]Image, color: Color) void; pub extern fn ImageDrawPixel(dst: [*c]Image, posX: c_int, posY: c_int, color: Color) void; pub extern fn ImageDrawPixelV(dst: [*c]Image, position: Vector2, color: Color) void; pub extern fn ImageDrawLine(dst: [*c]Image, startPosX: c_int, startPosY: c_int, endPosX: c_int, endPosY: c_int, color: Color) void; pub extern fn ImageDrawLineV(dst: [*c]Image, start: Vector2, end: Vector2, color: Color) void; pub extern fn ImageDrawCircle(dst: [*c]Image, centerX: c_int, centerY: c_int, radius: c_int, color: Color) void; pub extern fn ImageDrawCircleV(dst: [*c]Image, center: Vector2, radius: c_int, color: Color) void; pub extern fn ImageDrawRectangle(dst: [*c]Image, posX: c_int, posY: c_int, width: c_int, height: c_int, color: Color) void; pub extern fn ImageDrawRectangleV(dst: [*c]Image, position: Vector2, size: Vector2, color: Color) void; pub extern fn ImageDrawRectangleRec(dst: [*c]Image, rec: Rectangle, color: Color) void; pub extern fn ImageDrawRectangleLines(dst: [*c]Image, rec: Rectangle, thick: c_int, color: Color) void; pub extern fn ImageDraw(dst: [*c]Image, src: Image, srcRec: Rectangle, dstRec: Rectangle, tint: Color) void; pub extern fn ImageDrawText(dst: [*c]Image, text: [*c]const u8, posX: c_int, posY: c_int, fontSize: c_int, color: Color) void; pub extern fn ImageDrawTextEx(dst: [*c]Image, font: Font, text: [*c]const u8, position: Vector2, fontSize: f32, spacing: f32, tint: Color) void; pub extern fn LoadTexture(fileName: [*c]const u8) Texture2D; pub extern fn LoadTextureFromImage(image: Image) Texture2D; pub extern fn LoadTextureCubemap(image: Image, layout: c_int) TextureCubemap; pub extern fn LoadRenderTexture(width: c_int, height: c_int) RenderTexture2D; pub extern fn UnloadTexture(texture: Texture2D) void; pub extern fn UnloadRenderTexture(target: RenderTexture2D) void; pub extern fn UpdateTexture(texture: Texture2D, pixels: ?*const c_void) void; pub extern fn UpdateTextureRec(texture: Texture2D, rec: Rectangle, pixels: ?*const c_void) void; pub extern fn GenTextureMipmaps(texture: [*c]Texture2D) void; pub extern fn SetTextureFilter(texture: Texture2D, filter: c_int) void; pub extern fn SetTextureWrap(texture: Texture2D, wrap: c_int) void; pub extern fn DrawTexture(texture: Texture2D, posX: c_int, posY: c_int, tint: Color) void; pub extern fn DrawTextureV(texture: Texture2D, position: Vector2, tint: Color) void; pub extern fn DrawTextureEx(texture: Texture2D, position: Vector2, rotation: f32, scale: f32, tint: Color) void; pub extern fn DrawTextureRec(texture: Texture2D, source: Rectangle, position: Vector2, tint: Color) void; pub extern fn DrawTextureQuad(texture: Texture2D, tiling: Vector2, offset: Vector2, quad: Rectangle, tint: Color) void; pub extern fn DrawTextureTiled(texture: Texture2D, source: Rectangle, dest: Rectangle, origin: Vector2, rotation: f32, scale: f32, tint: Color) void; pub extern fn DrawTexturePro(texture: Texture2D, source: Rectangle, dest: Rectangle, origin: Vector2, rotation: f32, tint: Color) void; pub extern fn DrawTextureNPatch(texture: Texture2D, nPatchInfo: NPatchInfo, dest: Rectangle, origin: Vector2, rotation: f32, tint: Color) void; pub extern fn DrawTexturePoly(texture: Texture2D, center: Vector2, points: [*c]Vector2, texcoords: [*c]Vector2, pointsCount: c_int, tint: Color) void; pub extern fn Fade(color: Color, alpha: f32) Color; pub extern fn ColorToInt(color: Color) c_int; pub extern fn ColorNormalize(color: Color) Vector4; pub extern fn ColorFromNormalized(normalized: Vector4) Color; pub extern fn ColorToHSV(color: Color) Vector3; pub extern fn ColorFromHSV(hue: f32, saturation: f32, value: f32) Color; pub extern fn ColorAlpha(color: Color, alpha: f32) Color; pub extern fn ColorAlphaBlend(dst: Color, src: Color, tint: Color) Color; pub extern fn GetColor(hexValue: c_int) Color; pub extern fn GetPixelColor(srcPtr: ?*c_void, format: c_int) Color; pub extern fn SetPixelColor(dstPtr: ?*c_void, color: Color, format: c_int) void; pub extern fn GetPixelDataSize(width: c_int, height: c_int, format: c_int) c_int; pub extern fn GetFontDefault() Font; pub extern fn LoadFont(fileName: [*c]const u8) Font; pub extern fn LoadFontEx(fileName: [*c]const u8, fontSize: c_int, fontChars: [*c]c_int, charsCount: c_int) Font; pub extern fn LoadFontFromImage(image: Image, key: Color, firstChar: c_int) Font; pub extern fn LoadFontFromMemory(fileType: [*c]const u8, fileData: [*c]const u8, dataSize: c_int, fontSize: c_int, fontChars: [*c]c_int, charsCount: c_int) Font; pub extern fn LoadFontData(fileData: [*c]const u8, dataSize: c_int, fontSize: c_int, fontChars: [*c]c_int, charsCount: c_int, @"type": c_int) [*c]CharInfo; pub extern fn GenImageFontAtlas(chars: [*c]const CharInfo, recs: [*c][*c]Rectangle, charsCount: c_int, fontSize: c_int, padding: c_int, packMethod: c_int) Image; pub extern fn UnloadFontData(chars: [*c]CharInfo, charsCount: c_int) void; pub extern fn UnloadFont(font: Font) void; pub extern fn DrawFPS(posX: c_int, posY: c_int) void; pub extern fn DrawText(text: [*c]const u8, posX: c_int, posY: c_int, fontSize: c_int, color: Color) void; pub extern fn DrawTextEx(font: Font, text: [*c]const u8, position: Vector2, fontSize: f32, spacing: f32, tint: Color) void; pub extern fn DrawTextRec(font: Font, text: [*c]const u8, rec: Rectangle, fontSize: f32, spacing: f32, wordWrap: bool, tint: Color) void; pub extern fn DrawTextRecEx(font: Font, text: [*c]const u8, rec: Rectangle, fontSize: f32, spacing: f32, wordWrap: bool, tint: Color, selectStart: c_int, selectLength: c_int, selectTint: Color, selectBackTint: Color) void; pub extern fn DrawTextCodepoint(font: Font, codepoint: c_int, position: Vector2, fontSize: f32, tint: Color) void; pub extern fn MeasureText(text: [*c]const u8, fontSize: c_int) c_int; pub extern fn MeasureTextEx(font: Font, text: [*c]const u8, fontSize: f32, spacing: f32) Vector2; pub extern fn GetGlyphIndex(font: Font, codepoint: c_int) c_int; pub extern fn TextCopy(dst: [*c]u8, src: [*c]const u8) c_int; pub extern fn TextIsEqual(text1: [*c]const u8, text2: [*c]const u8) bool; pub extern fn TextLength(text: [*c]const u8) c_uint; pub extern fn TextFormat(text: [*c]const u8, ...) [*c]const u8; pub extern fn TextSubtext(text: [*c]const u8, position: c_int, length: c_int) [*c]const u8; pub extern fn TextReplace(text: [*c]u8, replace: [*c]const u8, by: [*c]const u8) [*c]u8; pub extern fn TextInsert(text: [*c]const u8, insert: [*c]const u8, position: c_int) [*c]u8; pub extern fn TextJoin(textList: [*c][*c]const u8, count: c_int, delimiter: [*c]const u8) [*c]const u8; pub extern fn TextSplit(text: [*c]const u8, delimiter: u8, count: [*c]c_int) [*c][*c]const u8; pub extern fn TextAppend(text: [*c]u8, append: [*c]const u8, position: [*c]c_int) void; pub extern fn TextFindIndex(text: [*c]const u8, find: [*c]const u8) c_int; pub extern fn TextToUpper(text: [*c]const u8) [*c]const u8; pub extern fn TextToLower(text: [*c]const u8) [*c]const u8; pub extern fn TextToPascal(text: [*c]const u8) [*c]const u8; pub extern fn TextToInteger(text: [*c]const u8) c_int; pub extern fn TextToUtf8(codepoints: [*c]c_int, length: c_int) [*c]u8; pub extern fn LoadCodepoints(text: [*c]const u8, count: [*c]c_int) [*c]c_int; pub extern fn UnloadCodepoints(codepoints: [*c]c_int) void; pub extern fn GetCodepointsCount(text: [*c]const u8) c_int; pub extern fn GetCodepoint(text: [*c]const u8, bytesProcessed: [*c]c_int) c_int; pub extern fn CodepointToUtf8(codepoint: c_int, byteLength: [*c]c_int) [*c]const u8; pub extern fn DrawLine3D(startPos: Vector3, endPos: Vector3, color: Color) void; pub extern fn DrawPoint3D(position: Vector3, color: Color) void; pub extern fn DrawCircle3D(center: Vector3, radius: f32, rotationAxis: Vector3, rotationAngle: f32, color: Color) void; pub extern fn DrawTriangle3D(v1: Vector3, v2: Vector3, v3: Vector3, color: Color) void; pub extern fn DrawTriangleStrip3D(points: [*c]Vector3, pointsCount: c_int, color: Color) void; pub extern fn DrawCube(position: Vector3, width: f32, height: f32, length: f32, color: Color) void; pub extern fn DrawCubeV(position: Vector3, size: Vector3, color: Color) void; pub extern fn DrawCubeWires(position: Vector3, width: f32, height: f32, length: f32, color: Color) void; pub extern fn DrawCubeWiresV(position: Vector3, size: Vector3, color: Color) void; pub extern fn DrawCubeTexture(texture: Texture2D, position: Vector3, width: f32, height: f32, length: f32, color: Color) void; pub extern fn DrawSphere(centerPos: Vector3, radius: f32, color: Color) void; pub extern fn DrawSphereEx(centerPos: Vector3, radius: f32, rings: c_int, slices: c_int, color: Color) void; pub extern fn DrawSphereWires(centerPos: Vector3, radius: f32, rings: c_int, slices: c_int, color: Color) void; pub extern fn DrawCylinder(position: Vector3, radiusTop: f32, radiusBottom: f32, height: f32, slices: c_int, color: Color) void; pub extern fn DrawCylinderWires(position: Vector3, radiusTop: f32, radiusBottom: f32, height: f32, slices: c_int, color: Color) void; pub extern fn DrawPlane(centerPos: Vector3, size: Vector2, color: Color) void; pub extern fn DrawRay(ray: Ray, color: Color) void; pub extern fn DrawGrid(slices: c_int, spacing: f32) void; pub extern fn LoadModel(fileName: [*c]const u8) Model; pub extern fn LoadModelFromMesh(mesh: Mesh) Model; pub extern fn UnloadModel(model: Model) void; pub extern fn UnloadModelKeepMeshes(model: Model) void; pub extern fn UploadMesh(mesh: [*c]Mesh, dynamic: bool) void; pub extern fn UpdateMeshBuffer(mesh: Mesh, index: c_int, data: ?*c_void, dataSize: c_int, offset: c_int) void; pub extern fn DrawMesh(mesh: Mesh, material: Material, transform: Matrix) void; pub extern fn DrawMeshInstanced(mesh: Mesh, material: Material, transforms: [*c]Matrix, instances: c_int) void; pub extern fn UnloadMesh(mesh: Mesh) void; pub extern fn ExportMesh(mesh: Mesh, fileName: [*c]const u8) bool; pub extern fn LoadMaterials(fileName: [*c]const u8, materialCount: [*c]c_int) [*c]Material; pub extern fn LoadMaterialDefault() Material; pub extern fn UnloadMaterial(material: Material) void; pub extern fn SetMaterialTexture(material: [*c]Material, mapType: c_int, texture: Texture2D) void; pub extern fn SetModelMeshMaterial(model: [*c]Model, meshId: c_int, materialId: c_int) void; pub extern fn LoadModelAnimations(fileName: [*c]const u8, animsCount: [*c]c_int) [*c]ModelAnimation; pub extern fn UpdateModelAnimation(model: Model, anim: ModelAnimation, frame: c_int) void; pub extern fn UnloadModelAnimation(anim: ModelAnimation) void; pub extern fn UnloadModelAnimations(animations: [*c]ModelAnimation, count: c_uint) void; pub extern fn IsModelAnimationValid(model: Model, anim: ModelAnimation) bool; pub extern fn GenMeshPoly(sides: c_int, radius: f32) Mesh; pub extern fn GenMeshPlane(width: f32, length: f32, resX: c_int, resZ: c_int) Mesh; pub extern fn GenMeshCube(width: f32, height: f32, length: f32) Mesh; pub extern fn GenMeshSphere(radius: f32, rings: c_int, slices: c_int) Mesh; pub extern fn GenMeshHemiSphere(radius: f32, rings: c_int, slices: c_int) Mesh; pub extern fn GenMeshCylinder(radius: f32, height: f32, slices: c_int) Mesh; pub extern fn GenMeshTorus(radius: f32, size: f32, radSeg: c_int, sides: c_int) Mesh; pub extern fn GenMeshKnot(radius: f32, size: f32, radSeg: c_int, sides: c_int) Mesh; pub extern fn GenMeshHeightmap(heightmap: Image, size: Vector3) Mesh; pub extern fn GenMeshCubicmap(cubicmap: Image, cubeSize: Vector3) Mesh; pub extern fn GetMeshBoundingBox(mesh: Mesh) BoundingBox; pub extern fn GenMeshTangents(mesh: [*c]Mesh) void; pub extern fn GenMeshBinormals(mesh: [*c]Mesh) void; pub extern fn DrawModel(model: Model, position: Vector3, scale: f32, tint: Color) void; pub extern fn DrawModelEx(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: f32, scale: Vector3, tint: Color) void; pub extern fn DrawModelWires(model: Model, position: Vector3, scale: f32, tint: Color) void; pub extern fn DrawModelWiresEx(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: f32, scale: Vector3, tint: Color) void; pub extern fn DrawBoundingBox(box: BoundingBox, color: Color) void; pub extern fn DrawBillboard(camera: Camera, texture: Texture2D, position: Vector3, size: f32, tint: Color) void; pub extern fn DrawBillboardRec(camera: Camera, texture: Texture2D, source: Rectangle, position: Vector3, size: Vector2, tint: Color) void; pub extern fn DrawBillboardPro(camera: Camera, texture: Texture2D, source: Rectangle, position: Vector3, size: Vector2, origin: Vector2, rotation: f32, tint: Color) void; pub extern fn CheckCollisionSpheres(center1: Vector3, radius1: f32, center2: Vector3, radius2: f32) bool; pub extern fn CheckCollisionBoxes(box1: BoundingBox, box2: BoundingBox) bool; pub extern fn CheckCollisionBoxSphere(box: BoundingBox, center: Vector3, radius: f32) bool; pub extern fn GetRayCollisionSphere(ray: Ray, center: Vector3, radius: f32) RayCollision; pub extern fn GetRayCollisionBox(ray: Ray, box: BoundingBox) RayCollision; pub extern fn GetRayCollisionModel(ray: Ray, model: Model) RayCollision; pub extern fn GetRayCollisionMesh(ray: Ray, mesh: Mesh, transform: Matrix) RayCollision; pub extern fn GetRayCollisionTriangle(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3) RayCollision; pub extern fn GetRayCollisionQuad(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3, p4: Vector3) RayCollision; pub extern fn InitAudioDevice() void; pub extern fn CloseAudioDevice() void; pub extern fn IsAudioDeviceReady() bool; pub extern fn SetMasterVolume(volume: f32) void; pub extern fn LoadWave(fileName: [*c]const u8) Wave; pub extern fn LoadWaveFromMemory(fileType: [*c]const u8, fileData: [*c]const u8, dataSize: c_int) Wave; pub extern fn LoadSound(fileName: [*c]const u8) Sound; pub extern fn LoadSoundFromWave(wave: Wave) Sound; pub extern fn UpdateSound(sound: Sound, data: ?*const c_void, samplesCount: c_int) void; pub extern fn UnloadWave(wave: Wave) void; pub extern fn UnloadSound(sound: Sound) void; pub extern fn ExportWave(wave: Wave, fileName: [*c]const u8) bool; pub extern fn ExportWaveAsCode(wave: Wave, fileName: [*c]const u8) bool; pub extern fn PlaySound(sound: Sound) void; pub extern fn StopSound(sound: Sound) void; pub extern fn PauseSound(sound: Sound) void; pub extern fn ResumeSound(sound: Sound) void; pub extern fn PlaySoundMulti(sound: Sound) void; pub extern fn StopSoundMulti() void; pub extern fn GetSoundsPlaying() c_int; pub extern fn IsSoundPlaying(sound: Sound) bool; pub extern fn SetSoundVolume(sound: Sound, volume: f32) void; pub extern fn SetSoundPitch(sound: Sound, pitch: f32) void; pub extern fn WaveFormat(wave: [*c]Wave, sampleRate: c_int, sampleSize: c_int, channels: c_int) void; pub extern fn WaveCopy(wave: Wave) Wave; pub extern fn WaveCrop(wave: [*c]Wave, initSample: c_int, finalSample: c_int) void; pub extern fn LoadWaveSamples(wave: Wave) [*c]f32; pub extern fn UnloadWaveSamples(samples: [*c]f32) void; pub extern fn LoadMusicStream(fileName: [*c]const u8) Music; pub extern fn LoadMusicStreamFromMemory(fileType: [*c]const u8, data: [*c]u8, dataSize: c_int) Music; pub extern fn UnloadMusicStream(music: Music) void; pub extern fn PlayMusicStream(music: Music) void; pub extern fn IsMusicStreamPlaying(music: Music) bool; pub extern fn UpdateMusicStream(music: Music) void; pub extern fn StopMusicStream(music: Music) void; pub extern fn PauseMusicStream(music: Music) void; pub extern fn ResumeMusicStream(music: Music) void; pub extern fn SetMusicVolume(music: Music, volume: f32) void; pub extern fn SetMusicPitch(music: Music, pitch: f32) void; pub extern fn GetMusicTimeLength(music: Music) f32; pub extern fn GetMusicTimePlayed(music: Music) f32; pub extern fn LoadAudioStream(sampleRate: c_uint, sampleSize: c_uint, channels: c_uint) AudioStream; pub extern fn UnloadAudioStream(stream: AudioStream) void; pub extern fn UpdateAudioStream(stream: AudioStream, data: ?*const c_void, samplesCount: c_int) void; pub extern fn IsAudioStreamProcessed(stream: AudioStream) bool; pub extern fn PlayAudioStream(stream: AudioStream) void; pub extern fn PauseAudioStream(stream: AudioStream) void; pub extern fn ResumeAudioStream(stream: AudioStream) void; pub extern fn IsAudioStreamPlaying(stream: AudioStream) bool; pub extern fn StopAudioStream(stream: AudioStream) void; pub extern fn SetAudioStreamVolume(stream: AudioStream, volume: f32) void; pub extern fn SetAudioStreamPitch(stream: AudioStream, pitch: f32) void; pub extern fn SetAudioStreamBufferSizeDefault(size: c_int) void; pub const __INTMAX_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `LL`"); // (no file):66:9 pub const __UINTMAX_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `ULL`"); // (no file):72:9 pub const __INT64_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `LL`"); // (no file):164:9 pub const __UINT32_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `U`"); // (no file):186:9 pub const __UINT64_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `ULL`"); // (no file):194:9 pub const __seg_gs = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):315:9 pub const __seg_fs = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):316:9 pub const __declspec = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):372:9 pub const _cdecl = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):373:9 pub const __cdecl = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):374:9 pub const _stdcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):375:9 pub const __stdcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):376:9 pub const _fastcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):377:9 pub const __fastcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):378:9 pub const _thiscall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):379:9 pub const __thiscall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):380:9 pub const _pascal = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):381:9 pub const __pascal = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):382:9 pub const va_start = @compileError("unable to translate macro: undefined identifier `__builtin_va_start`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:17:9 pub const va_end = @compileError("unable to translate macro: undefined identifier `__builtin_va_end`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:18:9 pub const va_arg = @compileError("unable to translate macro: undefined identifier `__builtin_va_arg`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:19:9 pub const __va_copy = @compileError("unable to translate macro: undefined identifier `__builtin_va_copy`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:24:9 pub const va_copy = @compileError("unable to translate macro: undefined identifier `__builtin_va_copy`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:27:9 pub const RL_MALLOC = @compileError("unable to translate macro: undefined identifier `malloc`"); // .\3rd\raylib\src\raylib.h:111:13 pub const RL_CALLOC = @compileError("unable to translate macro: undefined identifier `calloc`"); // .\3rd\raylib\src\raylib.h:114:13 pub const RL_REALLOC = @compileError("unable to translate macro: undefined identifier `realloc`"); // .\3rd\raylib\src\raylib.h:117:13 pub const RL_FREE = @compileError("unable to translate macro: undefined identifier `free`"); // .\3rd\raylib\src\raylib.h:120:13 pub const __llvm__ = @as(c_int, 1); pub const __clang__ = @as(c_int, 1); pub const __clang_major__ = @as(c_int, 13); pub const __clang_minor__ = @as(c_int, 0); pub const __clang_patchlevel__ = @as(c_int, 0); pub const __clang_version__ = "13.0.0 (https://github.com/llvm/llvm-project d7b669b3a30345cfcdb2fde2af6f48aa4b94845d)"; pub const __GNUC__ = @as(c_int, 4); pub const __GNUC_MINOR__ = @as(c_int, 2); pub const __GNUC_PATCHLEVEL__ = @as(c_int, 1); pub const __GXX_ABI_VERSION = @as(c_int, 1002); pub const __ATOMIC_RELAXED = @as(c_int, 0); pub const __ATOMIC_CONSUME = @as(c_int, 1); pub const __ATOMIC_ACQUIRE = @as(c_int, 2); pub const __ATOMIC_RELEASE = @as(c_int, 3); pub const __ATOMIC_ACQ_REL = @as(c_int, 4); pub const __ATOMIC_SEQ_CST = @as(c_int, 5); pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = @as(c_int, 0); pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = @as(c_int, 1); pub const __OPENCL_MEMORY_SCOPE_DEVICE = @as(c_int, 2); pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = @as(c_int, 3); pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = @as(c_int, 4); pub const __PRAGMA_REDEFINE_EXTNAME = @as(c_int, 1); pub const __VERSION__ = "Clang 13.0.0 (https://github.com/llvm/llvm-project d7b669b3a30345cfcdb2fde2af6f48aa4b94845d)"; pub const __OBJC_BOOL_IS_BOOL = @as(c_int, 0); pub const __CONSTANT_CFSTRINGS__ = @as(c_int, 1); pub const __SEH__ = @as(c_int, 1); pub const __clang_literal_encoding__ = "UTF-8"; pub const __clang_wide_literal_encoding__ = "UTF-16"; pub const __OPTIMIZE__ = @as(c_int, 1); pub const __ORDER_LITTLE_ENDIAN__ = @as(c_int, 1234); pub const __ORDER_BIG_ENDIAN__ = @as(c_int, 4321); pub const __ORDER_PDP_ENDIAN__ = @as(c_int, 3412); pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__; pub const __LITTLE_ENDIAN__ = @as(c_int, 1); pub const __CHAR_BIT__ = @as(c_int, 8); pub const __SCHAR_MAX__ = @as(c_int, 127); pub const __SHRT_MAX__ = @as(c_int, 32767); pub const __INT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __LONG_MAX__ = @as(c_long, 2147483647); pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807); pub const __WCHAR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __WINT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __INTMAX_MAX__ = @as(c_longlong, 9223372036854775807); pub const __SIZE_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINTMAX_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __PTRDIFF_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INTPTR_MAX__ = @as(c_longlong, 9223372036854775807); pub const __UINTPTR_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __SIZEOF_DOUBLE__ = @as(c_int, 8); pub const __SIZEOF_FLOAT__ = @as(c_int, 4); pub const __SIZEOF_INT__ = @as(c_int, 4); pub const __SIZEOF_LONG__ = @as(c_int, 4); pub const __SIZEOF_LONG_DOUBLE__ = @as(c_int, 16); pub const __SIZEOF_LONG_LONG__ = @as(c_int, 8); pub const __SIZEOF_POINTER__ = @as(c_int, 8); pub const __SIZEOF_SHORT__ = @as(c_int, 2); pub const __SIZEOF_PTRDIFF_T__ = @as(c_int, 8); pub const __SIZEOF_SIZE_T__ = @as(c_int, 8); pub const __SIZEOF_WCHAR_T__ = @as(c_int, 2); pub const __SIZEOF_WINT_T__ = @as(c_int, 2); pub const __SIZEOF_INT128__ = @as(c_int, 16); pub const __INTMAX_TYPE__ = c_longlong; pub const __INTMAX_FMTd__ = "lld"; pub const __INTMAX_FMTi__ = "lli"; pub const __UINTMAX_TYPE__ = c_ulonglong; pub const __UINTMAX_FMTo__ = "llo"; pub const __UINTMAX_FMTu__ = "llu"; pub const __UINTMAX_FMTx__ = "llx"; pub const __UINTMAX_FMTX__ = "llX"; pub const __INTMAX_WIDTH__ = @as(c_int, 64); pub const __PTRDIFF_TYPE__ = c_longlong; pub const __PTRDIFF_FMTd__ = "lld"; pub const __PTRDIFF_FMTi__ = "lli"; pub const __PTRDIFF_WIDTH__ = @as(c_int, 64); pub const __INTPTR_TYPE__ = c_longlong; pub const __INTPTR_FMTd__ = "lld"; pub const __INTPTR_FMTi__ = "lli"; pub const __INTPTR_WIDTH__ = @as(c_int, 64); pub const __SIZE_TYPE__ = c_ulonglong; pub const __SIZE_FMTo__ = "llo"; pub const __SIZE_FMTu__ = "llu"; pub const __SIZE_FMTx__ = "llx"; pub const __SIZE_FMTX__ = "llX"; pub const __SIZE_WIDTH__ = @as(c_int, 64); pub const __WCHAR_TYPE__ = c_ushort; pub const __WCHAR_WIDTH__ = @as(c_int, 16); pub const __WINT_TYPE__ = c_ushort; pub const __WINT_WIDTH__ = @as(c_int, 16); pub const __SIG_ATOMIC_WIDTH__ = @as(c_int, 32); pub const __SIG_ATOMIC_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __CHAR16_TYPE__ = c_ushort; pub const __CHAR32_TYPE__ = c_uint; pub const __UINTMAX_WIDTH__ = @as(c_int, 64); pub const __UINTPTR_TYPE__ = c_ulonglong; pub const __UINTPTR_FMTo__ = "llo"; pub const __UINTPTR_FMTu__ = "llu"; pub const __UINTPTR_FMTx__ = "llx"; pub const __UINTPTR_FMTX__ = "llX"; pub const __UINTPTR_WIDTH__ = @as(c_int, 64); pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45); pub const __FLT_HAS_DENORM__ = @as(c_int, 1); pub const __FLT_DIG__ = @as(c_int, 6); pub const __FLT_DECIMAL_DIG__ = @as(c_int, 9); pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7); pub const __FLT_HAS_INFINITY__ = @as(c_int, 1); pub const __FLT_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __FLT_MANT_DIG__ = @as(c_int, 24); pub const __FLT_MAX_10_EXP__ = @as(c_int, 38); pub const __FLT_MAX_EXP__ = @as(c_int, 128); pub const __FLT_MAX__ = @as(f32, 3.40282347e+38); pub const __FLT_MIN_10_EXP__ = -@as(c_int, 37); pub const __FLT_MIN_EXP__ = -@as(c_int, 125); pub const __FLT_MIN__ = @as(f32, 1.17549435e-38); pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324; pub const __DBL_HAS_DENORM__ = @as(c_int, 1); pub const __DBL_DIG__ = @as(c_int, 15); pub const __DBL_DECIMAL_DIG__ = @as(c_int, 17); pub const __DBL_EPSILON__ = 2.2204460492503131e-16; pub const __DBL_HAS_INFINITY__ = @as(c_int, 1); pub const __DBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __DBL_MANT_DIG__ = @as(c_int, 53); pub const __DBL_MAX_10_EXP__ = @as(c_int, 308); pub const __DBL_MAX_EXP__ = @as(c_int, 1024); pub const __DBL_MAX__ = 1.7976931348623157e+308; pub const __DBL_MIN_10_EXP__ = -@as(c_int, 307); pub const __DBL_MIN_EXP__ = -@as(c_int, 1021); pub const __DBL_MIN__ = 2.2250738585072014e-308; pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951); pub const __LDBL_HAS_DENORM__ = @as(c_int, 1); pub const __LDBL_DIG__ = @as(c_int, 18); pub const __LDBL_DECIMAL_DIG__ = @as(c_int, 21); pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19); pub const __LDBL_HAS_INFINITY__ = @as(c_int, 1); pub const __LDBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __LDBL_MANT_DIG__ = @as(c_int, 64); pub const __LDBL_MAX_10_EXP__ = @as(c_int, 4932); pub const __LDBL_MAX_EXP__ = @as(c_int, 16384); pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932); pub const __LDBL_MIN_10_EXP__ = -@as(c_int, 4931); pub const __LDBL_MIN_EXP__ = -@as(c_int, 16381); pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932); pub const __POINTER_WIDTH__ = @as(c_int, 64); pub const __BIGGEST_ALIGNMENT__ = @as(c_int, 16); pub const __WCHAR_UNSIGNED__ = @as(c_int, 1); pub const __WINT_UNSIGNED__ = @as(c_int, 1); pub const __INT8_TYPE__ = i8; pub const __INT8_FMTd__ = "hhd"; pub const __INT8_FMTi__ = "hhi"; pub const __INT8_C_SUFFIX__ = ""; pub const __INT16_TYPE__ = c_short; pub const __INT16_FMTd__ = "hd"; pub const __INT16_FMTi__ = "hi"; pub const __INT16_C_SUFFIX__ = ""; pub const __INT32_TYPE__ = c_int; pub const __INT32_FMTd__ = "d"; pub const __INT32_FMTi__ = "i"; pub const __INT32_C_SUFFIX__ = ""; pub const __INT64_TYPE__ = c_longlong; pub const __INT64_FMTd__ = "lld"; pub const __INT64_FMTi__ = "lli"; pub const __UINT8_TYPE__ = u8; pub const __UINT8_FMTo__ = "hho"; pub const __UINT8_FMTu__ = "hhu"; pub const __UINT8_FMTx__ = "hhx"; pub const __UINT8_FMTX__ = "hhX"; pub const __UINT8_C_SUFFIX__ = ""; pub const __UINT8_MAX__ = @as(c_int, 255); pub const __INT8_MAX__ = @as(c_int, 127); pub const __UINT16_TYPE__ = c_ushort; pub const __UINT16_FMTo__ = "ho"; pub const __UINT16_FMTu__ = "hu"; pub const __UINT16_FMTx__ = "hx"; pub const __UINT16_FMTX__ = "hX"; pub const __UINT16_C_SUFFIX__ = ""; pub const __UINT16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __INT16_MAX__ = @as(c_int, 32767); pub const __UINT32_TYPE__ = c_uint; pub const __UINT32_FMTo__ = "o"; pub const __UINT32_FMTu__ = "u"; pub const __UINT32_FMTx__ = "x"; pub const __UINT32_FMTX__ = "X"; pub const __UINT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __INT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __UINT64_TYPE__ = c_ulonglong; pub const __UINT64_FMTo__ = "llo"; pub const __UINT64_FMTu__ = "llu"; pub const __UINT64_FMTx__ = "llx"; pub const __UINT64_FMTX__ = "llX"; pub const __UINT64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __INT64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_LEAST8_TYPE__ = i8; pub const __INT_LEAST8_MAX__ = @as(c_int, 127); pub const __INT_LEAST8_FMTd__ = "hhd"; pub const __INT_LEAST8_FMTi__ = "hhi"; pub const __UINT_LEAST8_TYPE__ = u8; pub const __UINT_LEAST8_MAX__ = @as(c_int, 255); pub const __UINT_LEAST8_FMTo__ = "hho"; pub const __UINT_LEAST8_FMTu__ = "hhu"; pub const __UINT_LEAST8_FMTx__ = "hhx"; pub const __UINT_LEAST8_FMTX__ = "hhX"; pub const __INT_LEAST16_TYPE__ = c_short; pub const __INT_LEAST16_MAX__ = @as(c_int, 32767); pub const __INT_LEAST16_FMTd__ = "hd"; pub const __INT_LEAST16_FMTi__ = "hi"; pub const __UINT_LEAST16_TYPE__ = c_ushort; pub const __UINT_LEAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_LEAST16_FMTo__ = "ho"; pub const __UINT_LEAST16_FMTu__ = "hu"; pub const __UINT_LEAST16_FMTx__ = "hx"; pub const __UINT_LEAST16_FMTX__ = "hX"; pub const __INT_LEAST32_TYPE__ = c_int; pub const __INT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_LEAST32_FMTd__ = "d"; pub const __INT_LEAST32_FMTi__ = "i"; pub const __UINT_LEAST32_TYPE__ = c_uint; pub const __UINT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_LEAST32_FMTo__ = "o"; pub const __UINT_LEAST32_FMTu__ = "u"; pub const __UINT_LEAST32_FMTx__ = "x"; pub const __UINT_LEAST32_FMTX__ = "X"; pub const __INT_LEAST64_TYPE__ = c_longlong; pub const __INT_LEAST64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_LEAST64_FMTd__ = "lld"; pub const __INT_LEAST64_FMTi__ = "lli"; pub const __UINT_LEAST64_TYPE__ = c_ulonglong; pub const __UINT_LEAST64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINT_LEAST64_FMTo__ = "llo"; pub const __UINT_LEAST64_FMTu__ = "llu"; pub const __UINT_LEAST64_FMTx__ = "llx"; pub const __UINT_LEAST64_FMTX__ = "llX"; pub const __INT_FAST8_TYPE__ = i8; pub const __INT_FAST8_MAX__ = @as(c_int, 127); pub const __INT_FAST8_FMTd__ = "hhd"; pub const __INT_FAST8_FMTi__ = "hhi"; pub const __UINT_FAST8_TYPE__ = u8; pub const __UINT_FAST8_MAX__ = @as(c_int, 255); pub const __UINT_FAST8_FMTo__ = "hho"; pub const __UINT_FAST8_FMTu__ = "hhu"; pub const __UINT_FAST8_FMTx__ = "hhx"; pub const __UINT_FAST8_FMTX__ = "hhX"; pub const __INT_FAST16_TYPE__ = c_short; pub const __INT_FAST16_MAX__ = @as(c_int, 32767); pub const __INT_FAST16_FMTd__ = "hd"; pub const __INT_FAST16_FMTi__ = "hi"; pub const __UINT_FAST16_TYPE__ = c_ushort; pub const __UINT_FAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_FAST16_FMTo__ = "ho"; pub const __UINT_FAST16_FMTu__ = "hu"; pub const __UINT_FAST16_FMTx__ = "hx"; pub const __UINT_FAST16_FMTX__ = "hX"; pub const __INT_FAST32_TYPE__ = c_int; pub const __INT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_FAST32_FMTd__ = "d"; pub const __INT_FAST32_FMTi__ = "i"; pub const __UINT_FAST32_TYPE__ = c_uint; pub const __UINT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_FAST32_FMTo__ = "o"; pub const __UINT_FAST32_FMTu__ = "u"; pub const __UINT_FAST32_FMTx__ = "x"; pub const __UINT_FAST32_FMTX__ = "X"; pub const __INT_FAST64_TYPE__ = c_longlong; pub const __INT_FAST64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_FAST64_FMTd__ = "lld"; pub const __INT_FAST64_FMTi__ = "lli"; pub const __UINT_FAST64_TYPE__ = c_ulonglong; pub const __UINT_FAST64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINT_FAST64_FMTo__ = "llo"; pub const __UINT_FAST64_FMTu__ = "llu"; pub const __UINT_FAST64_FMTx__ = "llx"; pub const __UINT_FAST64_FMTX__ = "llX"; pub const __USER_LABEL_PREFIX__ = ""; pub const __FINITE_MATH_ONLY__ = @as(c_int, 0); pub const __GNUC_STDC_INLINE__ = @as(c_int, 1); pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = @as(c_int, 1); pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __PIC__ = @as(c_int, 2); pub const __pic__ = @as(c_int, 2); pub const __FLT_EVAL_METHOD__ = @as(c_int, 0); pub const __FLT_RADIX__ = @as(c_int, 2); pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__; pub const __SSP_STRONG__ = @as(c_int, 2); pub const __GCC_ASM_FLAG_OUTPUTS__ = @as(c_int, 1); pub const __code_model_small__ = @as(c_int, 1); pub const __amd64__ = @as(c_int, 1); pub const __amd64 = @as(c_int, 1); pub const __x86_64 = @as(c_int, 1); pub const __x86_64__ = @as(c_int, 1); pub const __SEG_GS = @as(c_int, 1); pub const __SEG_FS = @as(c_int, 1); pub const __corei7 = @as(c_int, 1); pub const __corei7__ = @as(c_int, 1); pub const __tune_corei7__ = @as(c_int, 1); pub const __REGISTER_PREFIX__ = ""; pub const __NO_MATH_INLINES = @as(c_int, 1); pub const __AES__ = @as(c_int, 1); pub const __PCLMUL__ = @as(c_int, 1); pub const __LAHF_SAHF__ = @as(c_int, 1); pub const __LZCNT__ = @as(c_int, 1); pub const __RDRND__ = @as(c_int, 1); pub const __FSGSBASE__ = @as(c_int, 1); pub const __BMI__ = @as(c_int, 1); pub const __BMI2__ = @as(c_int, 1); pub const __POPCNT__ = @as(c_int, 1); pub const __PRFCHW__ = @as(c_int, 1); pub const __RDSEED__ = @as(c_int, 1); pub const __ADX__ = @as(c_int, 1); pub const __MOVBE__ = @as(c_int, 1); pub const __FMA__ = @as(c_int, 1); pub const __F16C__ = @as(c_int, 1); pub const __FXSR__ = @as(c_int, 1); pub const __XSAVE__ = @as(c_int, 1); pub const __XSAVEOPT__ = @as(c_int, 1); pub const __INVPCID__ = @as(c_int, 1); pub const __AVX2__ = @as(c_int, 1); pub const __AVX__ = @as(c_int, 1); pub const __SSE4_2__ = @as(c_int, 1); pub const __SSE4_1__ = @as(c_int, 1); pub const __SSSE3__ = @as(c_int, 1); pub const __SSE3__ = @as(c_int, 1); pub const __SSE2__ = @as(c_int, 1); pub const __SSE2_MATH__ = @as(c_int, 1); pub const __SSE__ = @as(c_int, 1); pub const __SSE_MATH__ = @as(c_int, 1); pub const __MMX__ = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = @as(c_int, 1); pub const __SIZEOF_FLOAT128__ = @as(c_int, 16); pub const _WIN32 = @as(c_int, 1); pub const _WIN64 = @as(c_int, 1); pub const WIN32 = @as(c_int, 1); pub const __WIN32 = @as(c_int, 1); pub const __WIN32__ = @as(c_int, 1); pub const WINNT = @as(c_int, 1); pub const __WINNT = @as(c_int, 1); pub const __WINNT__ = @as(c_int, 1); pub const WIN64 = @as(c_int, 1); pub const __WIN64 = @as(c_int, 1); pub const __WIN64__ = @as(c_int, 1); pub const __MINGW64__ = @as(c_int, 1); pub const __MSVCRT__ = @as(c_int, 1); pub const __MINGW32__ = @as(c_int, 1); pub const __STDC__ = @as(c_int, 1); pub const __STDC_HOSTED__ = @as(c_int, 1); pub const __STDC_VERSION__ = @as(c_long, 201710); pub const __STDC_UTF_16__ = @as(c_int, 1); pub const __STDC_UTF_32__ = @as(c_int, 1); pub const _DEBUG = @as(c_int, 1); pub const RAYLIB_H = ""; pub const __STDARG_H = ""; pub const _VA_LIST = ""; pub const __GNUC_VA_LIST = @as(c_int, 1); pub const RAYLIB_VERSION = "3.8-dev"; pub const RLAPI = ""; pub const PI = @as(f32, 3.14159265358979323846); pub const DEG2RAD = PI / @as(f32, 180.0); pub const RAD2DEG = @as(f32, 180.0) / PI; pub inline fn CLITERAL(@"type": anytype) @TypeOf(@"type") { return @"type"; } pub const LIGHTGRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 200), @as(c_int, 200), @as(c_int, 200), @as(c_int, 255) }); pub const GRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 130), @as(c_int, 130), @as(c_int, 130), @as(c_int, 255) }); pub const DARKGRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 80), @as(c_int, 80), @as(c_int, 80), @as(c_int, 255) }); pub const YELLOW = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 253), @as(c_int, 249), @as(c_int, 0), @as(c_int, 255) }); pub const GOLD = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 203), @as(c_int, 0), @as(c_int, 255) }); pub const ORANGE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 161), @as(c_int, 0), @as(c_int, 255) }); pub const PINK = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 109), @as(c_int, 194), @as(c_int, 255) }); pub const RED = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 230), @as(c_int, 41), @as(c_int, 55), @as(c_int, 255) }); pub const MAROON = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 190), @as(c_int, 33), @as(c_int, 55), @as(c_int, 255) }); pub const GREEN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 228), @as(c_int, 48), @as(c_int, 255) }); pub const LIME = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 158), @as(c_int, 47), @as(c_int, 255) }); pub const DARKGREEN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 117), @as(c_int, 44), @as(c_int, 255) }); pub const SKYBLUE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 102), @as(c_int, 191), @as(c_int, 255), @as(c_int, 255) }); pub const BLUE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 121), @as(c_int, 241), @as(c_int, 255) }); pub const DARKBLUE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 82), @as(c_int, 172), @as(c_int, 255) }); pub const PURPLE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 200), @as(c_int, 122), @as(c_int, 255), @as(c_int, 255) }); pub const VIOLET = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 135), @as(c_int, 60), @as(c_int, 190), @as(c_int, 255) }); pub const DARKPURPLE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 112), @as(c_int, 31), @as(c_int, 126), @as(c_int, 255) }); pub const BEIGE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 211), @as(c_int, 176), @as(c_int, 131), @as(c_int, 255) }); pub const BROWN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 127), @as(c_int, 106), @as(c_int, 79), @as(c_int, 255) }); pub const DARKBROWN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 76), @as(c_int, 63), @as(c_int, 47), @as(c_int, 255) }); pub const WHITE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 255), @as(c_int, 255), @as(c_int, 255) }); pub const BLACK = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 0), @as(c_int, 0), @as(c_int, 255) }); pub const BLANK = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 0), @as(c_int, 0), @as(c_int, 0) }); pub const MAGENTA = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 0), @as(c_int, 255), @as(c_int, 255) }); pub const RAYWHITE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 245), @as(c_int, 245), @as(c_int, 245), @as(c_int, 255) }); pub const GetImageData = LoadImageColors; pub const FILTER_POINT = TEXTURE_FILTER_POINT; pub const FILTER_BILINEAR = TEXTURE_FILTER_BILINEAR; pub const MAP_DIFFUSE = MATERIAL_MAP_DIFFUSE; pub const UNCOMPRESSED_R8G8B8A8 = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; pub const __STDBOOL_H = ""; pub const @"bool" = bool; pub const @"true" = @as(c_int, 1); pub const @"false" = @as(c_int, 0); pub const __bool_true_false_are_defined = @as(c_int, 1); pub const MOUSE_LEFT_BUTTON = MOUSE_BUTTON_LEFT; pub const MOUSE_RIGHT_BUTTON = MOUSE_BUTTON_RIGHT; pub const MOUSE_MIDDLE_BUTTON = MOUSE_BUTTON_MIDDLE; pub const MATERIAL_MAP_DIFFUSE = MATERIAL_MAP_ALBEDO; pub const MATERIAL_MAP_SPECULAR = MATERIAL_MAP_METALNESS; pub const SHADER_LOC_MAP_DIFFUSE = SHADER_LOC_MAP_ALBEDO; pub const SHADER_LOC_MAP_SPECULAR = SHADER_LOC_MAP_METALNESS;
src/translate-c/raylib.zig
const std = @import("std"); const testing = std.testing; /// is a helper function for testing pub fn expectString(expected: []const u8, actual: []const u8) !void { testing.expect(std.mem.eql(u8, expected, actual)) catch |err| { std.log.err("expected: \'{s}\', got: \'{s}\'", .{ expected, actual }); return err; }; } /// Tuple is 2 valued tuple /// Stolen from <https://gist.github.com/adrusi/54ed2be2fbc6e9fb0c68f3c6f8706f9b> pub fn Tuple(comptime T0: type, comptime T1: type) type { return struct { const types = [_]type{ T0, T1 }; @"0": T0, @"1": T1, pub fn init(x0: T0, x1: T1) @This() { return .{ .@"0" = x0, .@"1" = x1 }; } pub fn unpack(self: @This(), vars: type) void { if (comptime @typeInfo(@TypeOf(vars[0])) != .Null) vars[0].* = self.@"0"; if (comptime @typeInfo(@TypeOf(vars[1])) != .Null) vars[1].* = self.@"1"; } pub fn set(self: *@This(), comptime index: usize, value: anytype) void { comptime { if (@TypeOf(value) != types[index]) { @compileLog("Invalid type for index" ++ index ++ ":" ++ @typeName(@TypeOf(value))); } } switch (comptime index) { 0 => self.@"0" = value, 1 => self.@"1" = value, else => @compileLog("Invalid index for Tuple: {}", index), } } pub fn get(self: *const @This(), comptime index: usize) switch (index) { 0 => T0, 1 => T1, else => @compileLog("Invalid index for Tuple: {}", index), } { return switch (comptime index) { 0 => self.@"0", 1 => self.@"1", else => undefined, }; } }; } const FieldError = error{ FieldNotFound, }; /// returns a field with the specified name pub fn getField(comptime T: type, comptime args: anytype, name: []const u8) !T { for (name) |c, i| if (c == '.') return getField(T, @field(args, name[0..i]), name[i + 1 ..]); return @field(args, name); } test "parse tag" { var t = comptime try getField([]const u8, .{ .foo = "bar" }, "foo"); try testing.expectEqual(t, "bar"); t = comptime try getField([]const u8, .{ .foo = .{ .bar = "baz" } }, "foo.bar"); try testing.expectEqual(t, "baz"); var t2 = comptime try getField([]const []const u8, .{ .foo = &.{ "bar", "baz" } }, "foo"); try testing.expectEqualSlices([]const u8, t2, &.{ "bar", "baz" }); } /// returns the index to the line pub fn indexToLineStack(index: usize, text: []const u8) Tuple(usize, usize) { var y: usize = 1; var since_new_line: usize = 1; for (text) |c, i| { if (c == '\n') { y += 1; since_new_line = 0; } if (i == index) return Tuple(usize, usize).init(y, since_new_line); since_new_line += 1; } return Tuple(usize, usize).init(0, 0); } pub fn getLine(line_number: usize, text: []const u8) []const u8 { var y: usize = 1; var x: usize = 0; var line_start: usize = 0; while (y <= line_number and x < text.len) : (x += 1) { if (text[x] == '\n') y += 1; if (y == line_number and text[x] == '\n') line_start = if (y > 1) x + 1 else x; } return text[line_start .. x - 1]; } test "getLine" { const text = "foo\nbar\nbaz\n"; const line = getLine(2, text); try testing.expectEqualSlices(u8, "bar", line); } test "indexToLineStack" { const t = indexToLineStack(8, "foo\nbar\nbaz"); try testing.expectEqual(Tuple(usize, usize).init(3, 1), t); }
src/utils.zig
const std = @import("std"); const upaya = @import("upaya"); const colors = upaya.colors; usingnamespace upaya.imgui; const stb = @import("stb"); var rects: []stb.stbrp_rect = undefined; var rect_count: usize = 20; var last_pack_result = true; const heuristics = [_][]const u8{ "Skyline", "Skyline BF" }; var heuristic: usize = 0; const tex_sizes = [_][]const u8{ "256", "512", "1024", "2048", "4096" }; var tex_size_index: usize = 2; var tex_size: c_int = 1024; pub fn main() !void { upaya.run(.{ .init = init, .update = update, .docking = false, }); } fn init() void { rects = upaya.mem.allocator.alloc(stb.stbrp_rect, rect_count) catch unreachable; regenerateRects(); solve(); } fn update() void { igSetNextWindowPos(.{}, ImGuiCond_Always, .{}); igSetNextWindowSize(.{ .x = @intToFloat(f32, upaya.sokol.sapp_width()), .y = @intToFloat(f32, upaya.sokol.sapp_height()), }, ImGuiCond_Always); if (igBegin("My First Window", null, ImGuiWindowFlags_NoTitleBar)) { igSetNextItemWidth(100); if (igBeginCombo("Heuristic", heuristics[heuristic].ptr, ImGuiComboFlags_None)) { for (heuristics) |h, i| { if (igSelectableBool(heuristics[i].ptr, i == heuristic, ImGuiSelectableFlags_None, .{})) { heuristic = i; solve(); } } igEndCombo(); } igSameLine(0, 15); igSetNextItemWidth(100); if (igBeginCombo("Tex Size", tex_sizes[tex_size_index].ptr, ImGuiComboFlags_None)) { for (tex_sizes) |h, i| { if (igSelectableBool(h.ptr, i == tex_size_index, ImGuiSelectableFlags_None, .{})) { tex_size_index = i; switch (i) { 0 => tex_size = 256, 1 => tex_size = 512, 2 => tex_size = 1024, 3 => tex_size = 2048, 4 => tex_size = 4096, else => {}, } solve(); } } igEndCombo(); } igSameLine(0, 15); igSetNextItemWidth(100); if (ogDrag(usize, "Total Rects", &rect_count, 0.4, 2, 300)) { upaya.mem.allocator.free(rects); rects = upaya.mem.allocator.alloc(stb.stbrp_rect, rect_count) catch unreachable; regenerateRects(); solve(); } igSameLine(0, 50); if (ogButton("Regenerate Rects")) { regenerateRects(); solve(); } if (igBeginChildEx("#child", 666, ogGetContentRegionAvail(), true, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_HorizontalScrollbar)) { var pos = ogGetCursorScreenPos(); const size = @intToFloat(f32, tex_size); ogAddRectFilled(igGetWindowDrawList(), pos, .{ .x = size, .y = size }, colors.rgbToU32(20, 20, 20)); _ = igInvisibleButton("##rects", .{ .x = size, .y = size }); const color = if (last_pack_result) colors.rgbToU32(0, 255, 0) else colors.rgbToU32(255, 0, 0); for (rects) |rect| { if (rect.was_packed == 0) continue; const tl = .{ .x = pos.x + @intToFloat(f32, rect.x), .y = pos.y + @intToFloat(f32, rect.y) }; ogAddRect(igGetWindowDrawList(), tl, .{ .x = @intToFloat(f32, rect.w), .y = @intToFloat(f32, rect.h) }, color, 1); } igEndChild(); } } igEnd(); } fn solve() void { var ctx: stb.stbrp_context = undefined; const rects_size = @sizeOf(stb.stbrp_rect) * rects.len; const node_count = 4096 * 2; var nodes: [node_count]stb.stbrp_node = undefined; stb.stbrp_init_target(&ctx, tex_size, tex_size, &nodes, node_count); stb.stbrp_setup_heuristic(&ctx, @intCast(c_int, heuristic)); last_pack_result = stb.stbrp_pack_rects(&ctx, rects.ptr, @intCast(c_int, rects.len)) == 1; } fn regenerateRects() void { var i: c_int = 0; while (i < rects.len) : (i += 1) { rects[@intCast(usize, i)] = .{ .id = i, .x = 0, .y = 0, .w = upaya.math.rand.range(c_ushort, 50, 300), .h = upaya.math.rand.range(c_ushort, 50, 300), }; } }
examples/texture_packer.zig
const builtin = @import("builtin"); const fmath = @import("index.zig"); pub fn round(x: var) -> @typeOf(x) { const T = @typeOf(x); switch (T) { f32 => @inlineCall(round32, x), f64 => @inlineCall(round64, x), else => @compileError("round not implemented for " ++ @typeName(T)), } } fn round32(x_: f32) -> f32 { var x = x_; const u = @bitCast(u32, x); const e = (u >> 23) & 0xFF; var y: f32 = undefined; if (e >= 0x7F+23) { return x; } if (u >> 31 != 0) { x = -x; } if (e < 0x7F-1) { fmath.forceEval(x + fmath.f32_toint); return 0 * @bitCast(f32, u); } { @setFloatMode(this, builtin.FloatMode.Strict); y = x + fmath.f32_toint - fmath.f32_toint - x; } if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 31 != 0) { -y } else { y } } fn round64(x_: f64) -> f64 { var x = x_; const u = @bitCast(u64, x); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF+52) { return x; } if (u >> 63 != 0) { x = -x; } if (e < 0x3ff-1) { fmath.forceEval(x + fmath.f64_toint); return 0 * @bitCast(f64, u); } { @setFloatMode(this, builtin.FloatMode.Strict); y = x + fmath.f64_toint - fmath.f64_toint - x; } if (y > 0.5) { y = y + x - 1; } else if (y <= -0.5) { y = y + x + 1; } else { y = y + x; } if (u >> 63 != 0) { -y } else { y } } test "round" { fmath.assert(round(f32(1.3)) == round32(1.3)); fmath.assert(round(f64(1.3)) == round64(1.3)); } test "round32" { fmath.assert(round32(1.3) == 1.0); fmath.assert(round32(-1.3) == -1.0); fmath.assert(round32(0.2) == 0.0); fmath.assert(round32(1.8) == 2.0); } test "round64" { fmath.assert(round64(1.3) == 1.0); fmath.assert(round64(-1.3) == -1.0); fmath.assert(round64(0.2) == 0.0); fmath.assert(round64(1.8) == 2.0); }
src/round.zig
pub const CATID_WcsPlugin = Guid.initString("a0b402e0-8240-405f-8a16-8a5b4df2f0dd"); pub const MAX_COLOR_CHANNELS = @as(u32, 8); pub const INTENT_PERCEPTUAL = @as(u32, 0); pub const INTENT_RELATIVE_COLORIMETRIC = @as(u32, 1); pub const INTENT_SATURATION = @as(u32, 2); pub const INTENT_ABSOLUTE_COLORIMETRIC = @as(u32, 3); pub const FLAG_EMBEDDEDPROFILE = @as(u32, 1); pub const FLAG_DEPENDENTONDATA = @as(u32, 2); pub const FLAG_ENABLE_CHROMATIC_ADAPTATION = @as(u32, 33554432); pub const ATTRIB_TRANSPARENCY = @as(u32, 1); pub const ATTRIB_MATTE = @as(u32, 2); pub const PROFILE_FILENAME = @as(u32, 1); pub const PROFILE_MEMBUFFER = @as(u32, 2); pub const PROFILE_READ = @as(u32, 1); pub const PROFILE_READWRITE = @as(u32, 2); pub const INDEX_DONT_CARE = @as(u32, 0); pub const CMM_FROM_PROFILE = @as(u32, 0); pub const ENUM_TYPE_VERSION = @as(u32, 768); pub const ET_DEVICENAME = @as(u32, 1); pub const ET_MEDIATYPE = @as(u32, 2); pub const ET_DITHERMODE = @as(u32, 4); pub const ET_RESOLUTION = @as(u32, 8); pub const ET_CMMTYPE = @as(u32, 16); pub const ET_CLASS = @as(u32, 32); pub const ET_DATACOLORSPACE = @as(u32, 64); pub const ET_CONNECTIONSPACE = @as(u32, 128); pub const ET_SIGNATURE = @as(u32, 256); pub const ET_PLATFORM = @as(u32, 512); pub const ET_PROFILEFLAGS = @as(u32, 1024); pub const ET_MANUFACTURER = @as(u32, 2048); pub const ET_MODEL = @as(u32, 4096); pub const ET_ATTRIBUTES = @as(u32, 8192); pub const ET_RENDERINGINTENT = @as(u32, 16384); pub const ET_CREATOR = @as(u32, 32768); pub const ET_DEVICECLASS = @as(u32, 65536); pub const ET_STANDARDDISPLAYCOLOR = @as(u32, 131072); pub const ET_EXTENDEDDISPLAYCOLOR = @as(u32, 262144); pub const PROOF_MODE = @as(u32, 1); pub const NORMAL_MODE = @as(u32, 2); pub const BEST_MODE = @as(u32, 3); pub const ENABLE_GAMUT_CHECKING = @as(u32, 65536); pub const USE_RELATIVE_COLORIMETRIC = @as(u32, 131072); pub const FAST_TRANSLATE = @as(u32, 262144); pub const PRESERVEBLACK = @as(u32, 1048576); pub const WCS_ALWAYS = @as(u32, 2097152); pub const SEQUENTIAL_TRANSFORM = @as(u32, 2155872256); pub const RESERVED = @as(u32, 2147483648); pub const CSA_A = @as(u32, 1); pub const CSA_ABC = @as(u32, 2); pub const CSA_DEF = @as(u32, 3); pub const CSA_DEFG = @as(u32, 4); pub const CSA_GRAY = @as(u32, 5); pub const CSA_RGB = @as(u32, 6); pub const CSA_CMYK = @as(u32, 7); pub const CSA_Lab = @as(u32, 8); pub const CMM_WIN_VERSION = @as(u32, 0); pub const CMM_IDENT = @as(u32, 1); pub const CMM_DRIVER_VERSION = @as(u32, 2); pub const CMM_DLL_VERSION = @as(u32, 3); pub const CMM_VERSION = @as(u32, 4); pub const CMM_DESCRIPTION = @as(u32, 5); pub const CMM_LOGOICON = @as(u32, 6); pub const CMS_FORWARD = @as(u32, 0); pub const CMS_BACKWARD = @as(u32, 1); pub const COLOR_MATCH_VERSION = @as(u32, 512); pub const CMS_DISABLEICM = @as(u32, 1); pub const CMS_ENABLEPROOFING = @as(u32, 2); pub const CMS_SETRENDERINTENT = @as(u32, 4); pub const CMS_SETPROOFINTENT = @as(u32, 8); pub const CMS_SETMONITORPROFILE = @as(u32, 16); pub const CMS_SETPRINTERPROFILE = @as(u32, 32); pub const CMS_SETTARGETPROFILE = @as(u32, 64); pub const CMS_USEHOOK = @as(u32, 128); pub const CMS_USEAPPLYCALLBACK = @as(u32, 256); pub const CMS_USEDESCRIPTION = @as(u32, 512); pub const CMS_DISABLEINTENT = @as(u32, 1024); pub const CMS_DISABLERENDERINTENT = @as(u32, 2048); pub const CMS_MONITOROVERFLOW = @as(i32, -2147483648); pub const CMS_PRINTEROVERFLOW = @as(i32, 1073741824); pub const CMS_TARGETOVERFLOW = @as(i32, 536870912); pub const DONT_USE_EMBEDDED_WCS_PROFILES = @as(i32, 1); pub const WCS_DEFAULT = @as(i32, 0); pub const WCS_ICCONLY = @as(i32, 65536); //-------------------------------------------------------------------------------- // Section: Types (49) //-------------------------------------------------------------------------------- pub const ICM_COMMAND = enum(u32) { ADDPROFILE = 1, DELETEPROFILE = 2, QUERYPROFILE = 3, SETDEFAULTPROFILE = 4, REGISTERICMATCHER = 5, UNREGISTERICMATCHER = 6, QUERYMATCH = 7, }; pub const ICM_ADDPROFILE = ICM_COMMAND.ADDPROFILE; pub const ICM_DELETEPROFILE = ICM_COMMAND.DELETEPROFILE; pub const ICM_QUERYPROFILE = ICM_COMMAND.QUERYPROFILE; pub const ICM_SETDEFAULTPROFILE = ICM_COMMAND.SETDEFAULTPROFILE; pub const ICM_REGISTERICMATCHER = ICM_COMMAND.REGISTERICMATCHER; pub const ICM_UNREGISTERICMATCHER = ICM_COMMAND.UNREGISTERICMATCHER; pub const ICM_QUERYMATCH = ICM_COMMAND.QUERYMATCH; pub const COLOR_MATCH_TO_TARGET_ACTION = enum(i32) { ENABLE = 1, DISABLE = 2, DELETE_TRANSFORM = 3, }; pub const CS_ENABLE = COLOR_MATCH_TO_TARGET_ACTION.ENABLE; pub const CS_DISABLE = COLOR_MATCH_TO_TARGET_ACTION.DISABLE; pub const CS_DELETE_TRANSFORM = COLOR_MATCH_TO_TARGET_ACTION.DELETE_TRANSFORM; // TODO: this type has a FreeFunc 'DeleteColorSpace', what can Zig do with this information? pub const HCOLORSPACE = *opaque{}; pub const LOGCOLORSPACEA = extern struct { lcsSignature: u32, lcsVersion: u32, lcsSize: u32, lcsCSType: i32, lcsIntent: i32, lcsEndpoints: CIEXYZTRIPLE, lcsGammaRed: u32, lcsGammaGreen: u32, lcsGammaBlue: u32, lcsFilename: [260]CHAR, }; pub const LOGCOLORSPACEW = extern struct { lcsSignature: u32, lcsVersion: u32, lcsSize: u32, lcsCSType: i32, lcsIntent: i32, lcsEndpoints: CIEXYZTRIPLE, lcsGammaRed: u32, lcsGammaGreen: u32, lcsGammaBlue: u32, lcsFilename: [260]u16, }; pub const ICMENUMPROCA = fn( param0: ?PSTR, param1: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const ICMENUMPROCW = fn( param0: ?PWSTR, param1: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const EMRCREATECOLORSPACE = extern struct { emr: EMR, ihCS: u32, lcs: LOGCOLORSPACEA, }; pub const EMRCREATECOLORSPACEW = extern struct { emr: EMR, ihCS: u32, lcs: LOGCOLORSPACEW, dwFlags: u32, cbData: u32, Data: [1]u8, }; pub const XYZColorF = extern struct { X: f32, Y: f32, Z: f32, }; pub const JChColorF = extern struct { J: f32, C: f32, h: f32, }; pub const JabColorF = extern struct { J: f32, a: f32, b: f32, }; pub const GamutShellTriangle = extern struct { aVertexIndex: [3]u32, }; pub const GamutShell = extern struct { JMin: f32, JMax: f32, cVertices: u32, cTriangles: u32, pVertices: ?*JabColorF, pTriangles: ?*GamutShellTriangle, }; pub const PrimaryJabColors = extern struct { red: JabColorF, yellow: JabColorF, green: JabColorF, cyan: JabColorF, blue: JabColorF, magenta: JabColorF, black: JabColorF, white: JabColorF, }; pub const PrimaryXYZColors = extern struct { red: XYZColorF, yellow: XYZColorF, green: XYZColorF, cyan: XYZColorF, blue: XYZColorF, magenta: XYZColorF, black: XYZColorF, white: XYZColorF, }; pub const GamutBoundaryDescription = extern struct { pPrimaries: ?*PrimaryJabColors, cNeutralSamples: u32, pNeutralSamples: ?*JabColorF, pReferenceShell: ?*GamutShell, pPlausibleShell: ?*GamutShell, pPossibleShell: ?*GamutShell, }; pub const BlackInformation = extern struct { fBlackOnly: BOOL, blackWeight: f32, }; const IID_IDeviceModelPlugIn_Value = Guid.initString("1cd63475-07c4-46fe-a903-d655316d11fd"); pub const IID_IDeviceModelPlugIn = &IID_IDeviceModelPlugIn_Value; pub const IDeviceModelPlugIn = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDeviceModelPlugIn, bstrXml: ?BSTR, cNumModels: u32, iModelPosition: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNumChannels: fn( self: *const IDeviceModelPlugIn, pNumChannels: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeviceToColorimetricColors: fn( self: *const IDeviceModelPlugIn, cColors: u32, cChannels: u32, pDeviceValues: ?*const f32, pXYZColors: [*]XYZColorF, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ColorimetricToDeviceColors: fn( self: *const IDeviceModelPlugIn, cColors: u32, cChannels: u32, pXYZColors: [*]const XYZColorF, pDeviceValues: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ColorimetricToDeviceColorsWithBlack: fn( self: *const IDeviceModelPlugIn, cColors: u32, cChannels: u32, pXYZColors: [*]const XYZColorF, pBlackInformation: [*]const BlackInformation, pDeviceValues: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTransformDeviceModelInfo: fn( self: *const IDeviceModelPlugIn, iModelPosition: u32, pIDeviceModelOther: ?*IDeviceModelPlugIn, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrimarySamples: fn( self: *const IDeviceModelPlugIn, pPrimaryColor: ?*PrimaryXYZColors, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGamutBoundaryMeshSize: fn( self: *const IDeviceModelPlugIn, pNumVertices: ?*u32, pNumTriangles: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGamutBoundaryMesh: fn( self: *const IDeviceModelPlugIn, cChannels: u32, cVertices: u32, cTriangles: u32, pVertices: ?*f32, pTriangles: [*]GamutShellTriangle, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNeutralAxisSize: fn( self: *const IDeviceModelPlugIn, pcColors: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNeutralAxis: fn( self: *const IDeviceModelPlugIn, cColors: u32, pXYZColors: [*]XYZColorF, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_Initialize(self: *const T, bstrXml: ?BSTR, cNumModels: u32, iModelPosition: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).Initialize(@ptrCast(*const IDeviceModelPlugIn, self), bstrXml, cNumModels, iModelPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_GetNumChannels(self: *const T, pNumChannels: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).GetNumChannels(@ptrCast(*const IDeviceModelPlugIn, self), pNumChannels); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_DeviceToColorimetricColors(self: *const T, cColors: u32, cChannels: u32, pDeviceValues: ?*const f32, pXYZColors: [*]XYZColorF) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).DeviceToColorimetricColors(@ptrCast(*const IDeviceModelPlugIn, self), cColors, cChannels, pDeviceValues, pXYZColors); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_ColorimetricToDeviceColors(self: *const T, cColors: u32, cChannels: u32, pXYZColors: [*]const XYZColorF, pDeviceValues: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).ColorimetricToDeviceColors(@ptrCast(*const IDeviceModelPlugIn, self), cColors, cChannels, pXYZColors, pDeviceValues); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_ColorimetricToDeviceColorsWithBlack(self: *const T, cColors: u32, cChannels: u32, pXYZColors: [*]const XYZColorF, pBlackInformation: [*]const BlackInformation, pDeviceValues: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).ColorimetricToDeviceColorsWithBlack(@ptrCast(*const IDeviceModelPlugIn, self), cColors, cChannels, pXYZColors, pBlackInformation, pDeviceValues); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_SetTransformDeviceModelInfo(self: *const T, iModelPosition: u32, pIDeviceModelOther: ?*IDeviceModelPlugIn) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).SetTransformDeviceModelInfo(@ptrCast(*const IDeviceModelPlugIn, self), iModelPosition, pIDeviceModelOther); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_GetPrimarySamples(self: *const T, pPrimaryColor: ?*PrimaryXYZColors) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).GetPrimarySamples(@ptrCast(*const IDeviceModelPlugIn, self), pPrimaryColor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_GetGamutBoundaryMeshSize(self: *const T, pNumVertices: ?*u32, pNumTriangles: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).GetGamutBoundaryMeshSize(@ptrCast(*const IDeviceModelPlugIn, self), pNumVertices, pNumTriangles); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_GetGamutBoundaryMesh(self: *const T, cChannels: u32, cVertices: u32, cTriangles: u32, pVertices: ?*f32, pTriangles: [*]GamutShellTriangle) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).GetGamutBoundaryMesh(@ptrCast(*const IDeviceModelPlugIn, self), cChannels, cVertices, cTriangles, pVertices, pTriangles); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_GetNeutralAxisSize(self: *const T, pcColors: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).GetNeutralAxisSize(@ptrCast(*const IDeviceModelPlugIn, self), pcColors); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDeviceModelPlugIn_GetNeutralAxis(self: *const T, cColors: u32, pXYZColors: [*]XYZColorF) callconv(.Inline) HRESULT { return @ptrCast(*const IDeviceModelPlugIn.VTable, self.vtable).GetNeutralAxis(@ptrCast(*const IDeviceModelPlugIn, self), cColors, pXYZColors); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IGamutMapModelPlugIn_Value = Guid.initString("2dd80115-ad1e-41f6-a219-a4f4b583d1f9"); pub const IID_IGamutMapModelPlugIn = &IID_IGamutMapModelPlugIn_Value; pub const IGamutMapModelPlugIn = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IGamutMapModelPlugIn, bstrXml: ?BSTR, pSrcPlugIn: ?*IDeviceModelPlugIn, pDestPlugIn: ?*IDeviceModelPlugIn, pSrcGBD: ?*GamutBoundaryDescription, pDestGBD: ?*GamutBoundaryDescription, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SourceToDestinationAppearanceColors: fn( self: *const IGamutMapModelPlugIn, cColors: u32, pInputColors: [*]const JChColorF, pOutputColors: [*]JChColorF, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGamutMapModelPlugIn_Initialize(self: *const T, bstrXml: ?BSTR, pSrcPlugIn: ?*IDeviceModelPlugIn, pDestPlugIn: ?*IDeviceModelPlugIn, pSrcGBD: ?*GamutBoundaryDescription, pDestGBD: ?*GamutBoundaryDescription) callconv(.Inline) HRESULT { return @ptrCast(*const IGamutMapModelPlugIn.VTable, self.vtable).Initialize(@ptrCast(*const IGamutMapModelPlugIn, self), bstrXml, pSrcPlugIn, pDestPlugIn, pSrcGBD, pDestGBD); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IGamutMapModelPlugIn_SourceToDestinationAppearanceColors(self: *const T, cColors: u32, pInputColors: [*]const JChColorF, pOutputColors: [*]JChColorF) callconv(.Inline) HRESULT { return @ptrCast(*const IGamutMapModelPlugIn.VTable, self.vtable).SourceToDestinationAppearanceColors(@ptrCast(*const IGamutMapModelPlugIn, self), cColors, pInputColors, pOutputColors); } };} pub usingnamespace MethodMixin(@This()); }; pub const NAMED_PROFILE_INFO = extern struct { dwFlags: u32, dwCount: u32, dwCountDevCoordinates: u32, szPrefix: [32]i8, szSuffix: [32]i8, }; pub const GRAYCOLOR = extern struct { gray: u16, }; pub const RGBCOLOR = extern struct { red: u16, green: u16, blue: u16, }; pub const CMYKCOLOR = extern struct { cyan: u16, magenta: u16, yellow: u16, black: u16, }; pub const XYZCOLOR = extern struct { X: u16, Y: u16, Z: u16, }; pub const YxyCOLOR = extern struct { Y: u16, x: u16, y: u16, }; pub const LabCOLOR = extern struct { L: u16, a: u16, b: u16, }; pub const GENERIC3CHANNEL = extern struct { ch1: u16, ch2: u16, ch3: u16, }; pub const NAMEDCOLOR = extern struct { dwIndex: u32, }; pub const HiFiCOLOR = extern struct { channel: [8]u8, }; pub const COLOR = extern union { gray: GRAYCOLOR, rgb: RGBCOLOR, cmyk: CMYKCOLOR, XYZ: XYZCOLOR, Yxy: YxyCOLOR, Lab: LabCOLOR, gen3ch: GENERIC3CHANNEL, named: NAMEDCOLOR, hifi: HiFiCOLOR, Anonymous: extern struct { reserved1: u32, reserved2: ?*anyopaque, }, }; pub const COLORTYPE = enum(i32) { GRAY = 1, RGB = 2, XYZ = 3, Yxy = 4, Lab = 5, @"3_CHANNEL" = 6, CMYK = 7, @"5_CHANNEL" = 8, @"6_CHANNEL" = 9, @"7_CHANNEL" = 10, @"8_CHANNEL" = 11, NAMED = 12, }; pub const COLOR_GRAY = COLORTYPE.GRAY; pub const COLOR_RGB = COLORTYPE.RGB; pub const COLOR_XYZ = COLORTYPE.XYZ; pub const COLOR_Yxy = COLORTYPE.Yxy; pub const COLOR_Lab = COLORTYPE.Lab; pub const COLOR_3_CHANNEL = COLORTYPE.@"3_CHANNEL"; pub const COLOR_CMYK = COLORTYPE.CMYK; pub const COLOR_5_CHANNEL = COLORTYPE.@"5_CHANNEL"; pub const COLOR_6_CHANNEL = COLORTYPE.@"6_CHANNEL"; pub const COLOR_7_CHANNEL = COLORTYPE.@"7_CHANNEL"; pub const COLOR_8_CHANNEL = COLORTYPE.@"8_CHANNEL"; pub const COLOR_NAMED = COLORTYPE.NAMED; pub const COLORPROFILETYPE = enum(i32) { ICC = 0, DMP = 1, CAMP = 2, GMMP = 3, }; pub const CPT_ICC = COLORPROFILETYPE.ICC; pub const CPT_DMP = COLORPROFILETYPE.DMP; pub const CPT_CAMP = COLORPROFILETYPE.CAMP; pub const CPT_GMMP = COLORPROFILETYPE.GMMP; pub const COLORPROFILESUBTYPE = enum(i32) { PERCEPTUAL = 0, RELATIVE_COLORIMETRIC = 1, SATURATION = 2, ABSOLUTE_COLORIMETRIC = 3, NONE = 4, RGB_WORKING_SPACE = 5, CUSTOM_WORKING_SPACE = 6, STANDARD_DISPLAY_COLOR_MODE = 7, EXTENDED_DISPLAY_COLOR_MODE = 8, }; pub const CPST_PERCEPTUAL = COLORPROFILESUBTYPE.PERCEPTUAL; pub const CPST_RELATIVE_COLORIMETRIC = COLORPROFILESUBTYPE.RELATIVE_COLORIMETRIC; pub const CPST_SATURATION = COLORPROFILESUBTYPE.SATURATION; pub const CPST_ABSOLUTE_COLORIMETRIC = COLORPROFILESUBTYPE.ABSOLUTE_COLORIMETRIC; pub const CPST_NONE = COLORPROFILESUBTYPE.NONE; pub const CPST_RGB_WORKING_SPACE = COLORPROFILESUBTYPE.RGB_WORKING_SPACE; pub const CPST_CUSTOM_WORKING_SPACE = COLORPROFILESUBTYPE.CUSTOM_WORKING_SPACE; pub const CPST_STANDARD_DISPLAY_COLOR_MODE = COLORPROFILESUBTYPE.STANDARD_DISPLAY_COLOR_MODE; pub const CPST_EXTENDED_DISPLAY_COLOR_MODE = COLORPROFILESUBTYPE.EXTENDED_DISPLAY_COLOR_MODE; pub const COLORDATATYPE = enum(i32) { BYTE = 1, WORD = 2, FLOAT = 3, S2DOT13FIXED = 4, @"10b_R10G10B10A2" = 5, @"10b_R10G10B10A2_XR" = 6, FLOAT16 = 7, }; pub const COLOR_BYTE = COLORDATATYPE.BYTE; pub const COLOR_WORD = COLORDATATYPE.WORD; pub const COLOR_FLOAT = COLORDATATYPE.FLOAT; pub const COLOR_S2DOT13FIXED = COLORDATATYPE.S2DOT13FIXED; pub const COLOR_10b_R10G10B10A2 = COLORDATATYPE.@"10b_R10G10B10A2"; pub const COLOR_10b_R10G10B10A2_XR = COLORDATATYPE.@"10b_R10G10B10A2_XR"; pub const COLOR_FLOAT16 = COLORDATATYPE.FLOAT16; pub const BMFORMAT = enum(i32) { x555RGB = 0, x555XYZ = 257, x555Yxy = 258, x555Lab = 259, x555G3CH = 260, RGBTRIPLETS = 2, BGRTRIPLETS = 4, XYZTRIPLETS = 513, YxyTRIPLETS = 514, LabTRIPLETS = 515, G3CHTRIPLETS = 516, @"5CHANNEL" = 517, @"6CHANNEL" = 518, @"7CHANNEL" = 519, @"8CHANNEL" = 520, GRAY = 521, xRGBQUADS = 8, xBGRQUADS = 16, xG3CHQUADS = 772, KYMCQUADS = 773, CMYKQUADS = 32, @"10b_RGB" = 9, @"10b_XYZ" = 1025, @"10b_Yxy" = 1026, @"10b_Lab" = 1027, @"10b_G3CH" = 1028, NAMED_INDEX = 1029, @"16b_RGB" = 10, @"16b_XYZ" = 1281, @"16b_Yxy" = 1282, @"16b_Lab" = 1283, @"16b_G3CH" = 1284, @"16b_GRAY" = 1285, @"565RGB" = 1, @"32b_scRGB" = 1537, @"32b_scARGB" = 1538, S2DOT13FIXED_scRGB = 1539, S2DOT13FIXED_scARGB = 1540, R10G10B10A2 = 1793, R10G10B10A2_XR = 1794, R16G16B16A16_FLOAT = 1795, }; pub const BM_x555RGB = BMFORMAT.x555RGB; pub const BM_x555XYZ = BMFORMAT.x555XYZ; pub const BM_x555Yxy = BMFORMAT.x555Yxy; pub const BM_x555Lab = BMFORMAT.x555Lab; pub const BM_x555G3CH = BMFORMAT.x555G3CH; pub const BM_RGBTRIPLETS = BMFORMAT.RGBTRIPLETS; pub const BM_BGRTRIPLETS = BMFORMAT.BGRTRIPLETS; pub const BM_XYZTRIPLETS = BMFORMAT.XYZTRIPLETS; pub const BM_YxyTRIPLETS = BMFORMAT.YxyTRIPLETS; pub const BM_LabTRIPLETS = BMFORMAT.LabTRIPLETS; pub const BM_G3CHTRIPLETS = BMFORMAT.G3CHTRIPLETS; pub const BM_5CHANNEL = BMFORMAT.@"5CHANNEL"; pub const BM_6CHANNEL = BMFORMAT.@"6CHANNEL"; pub const BM_7CHANNEL = BMFORMAT.@"7CHANNEL"; pub const BM_8CHANNEL = BMFORMAT.@"8CHANNEL"; pub const BM_GRAY = BMFORMAT.GRAY; pub const BM_xRGBQUADS = BMFORMAT.xRGBQUADS; pub const BM_xBGRQUADS = BMFORMAT.xBGRQUADS; pub const BM_xG3CHQUADS = BMFORMAT.xG3CHQUADS; pub const BM_KYMCQUADS = BMFORMAT.KYMCQUADS; pub const BM_CMYKQUADS = BMFORMAT.CMYKQUADS; pub const BM_10b_RGB = BMFORMAT.@"10b_RGB"; pub const BM_10b_XYZ = BMFORMAT.@"10b_XYZ"; pub const BM_10b_Yxy = BMFORMAT.@"10b_Yxy"; pub const BM_10b_Lab = BMFORMAT.@"10b_Lab"; pub const BM_10b_G3CH = BMFORMAT.@"10b_G3CH"; pub const BM_NAMED_INDEX = BMFORMAT.NAMED_INDEX; pub const BM_16b_RGB = BMFORMAT.@"16b_RGB"; pub const BM_16b_XYZ = BMFORMAT.@"16b_XYZ"; pub const BM_16b_Yxy = BMFORMAT.@"16b_Yxy"; pub const BM_16b_Lab = BMFORMAT.@"16b_Lab"; pub const BM_16b_G3CH = BMFORMAT.@"16b_G3CH"; pub const BM_16b_GRAY = BMFORMAT.@"16b_GRAY"; pub const BM_565RGB = BMFORMAT.@"565RGB"; pub const BM_32b_scRGB = BMFORMAT.@"32b_scRGB"; pub const BM_32b_scARGB = BMFORMAT.@"32b_scARGB"; pub const BM_S2DOT13FIXED_scRGB = BMFORMAT.S2DOT13FIXED_scRGB; pub const BM_S2DOT13FIXED_scARGB = BMFORMAT.S2DOT13FIXED_scARGB; pub const BM_R10G10B10A2 = BMFORMAT.R10G10B10A2; pub const BM_R10G10B10A2_XR = BMFORMAT.R10G10B10A2_XR; pub const BM_R16G16B16A16_FLOAT = BMFORMAT.R16G16B16A16_FLOAT; pub const LPBMCALLBACKFN = fn( param0: u32, param1: u32, param2: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PROFILEHEADER = extern struct { phSize: u32, phCMMType: u32, phVersion: u32, phClass: u32, phDataColorSpace: u32, phConnectionSpace: u32, phDateTime: [3]u32, phSignature: u32, phPlatform: u32, phProfileFlags: u32, phManufacturer: u32, phModel: u32, phAttributes: [2]u32, phRenderingIntent: u32, phIlluminant: CIEXYZ, phCreator: u32, phReserved: [44]u8, }; pub const PROFILE = extern struct { dwType: u32, pProfileData: ?*anyopaque, cbDataSize: u32, }; pub const ENUMTYPEA = extern struct { dwSize: u32, dwVersion: u32, dwFields: u32, pDeviceName: ?[*:0]const u8, dwMediaType: u32, dwDitheringMode: u32, dwResolution: [2]u32, dwCMMType: u32, dwClass: u32, dwDataColorSpace: u32, dwConnectionSpace: u32, dwSignature: u32, dwPlatform: u32, dwProfileFlags: u32, dwManufacturer: u32, dwModel: u32, dwAttributes: [2]u32, dwRenderingIntent: u32, dwCreator: u32, dwDeviceClass: u32, }; pub const ENUMTYPEW = extern struct { dwSize: u32, dwVersion: u32, dwFields: u32, pDeviceName: ?[*:0]const u16, dwMediaType: u32, dwDitheringMode: u32, dwResolution: [2]u32, dwCMMType: u32, dwClass: u32, dwDataColorSpace: u32, dwConnectionSpace: u32, dwSignature: u32, dwPlatform: u32, dwProfileFlags: u32, dwManufacturer: u32, dwModel: u32, dwAttributes: [2]u32, dwRenderingIntent: u32, dwCreator: u32, dwDeviceClass: u32, }; pub const WCS_PROFILE_MANAGEMENT_SCOPE = enum(i32) { SYSTEM_WIDE = 0, CURRENT_USER = 1, }; pub const WCS_PROFILE_MANAGEMENT_SCOPE_SYSTEM_WIDE = WCS_PROFILE_MANAGEMENT_SCOPE.SYSTEM_WIDE; pub const WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER = WCS_PROFILE_MANAGEMENT_SCOPE.CURRENT_USER; pub const PCMSCALLBACKW = fn( param0: ?*COLORMATCHSETUPW, param1: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PCMSCALLBACKA = fn( param0: ?*COLORMATCHSETUPA, param1: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const COLORMATCHSETUPW = extern struct { dwSize: u32, dwVersion: u32, dwFlags: u32, hwndOwner: ?HWND, pSourceName: ?[*:0]const u16, pDisplayName: ?[*:0]const u16, pPrinterName: ?[*:0]const u16, dwRenderIntent: u32, dwProofingIntent: u32, pMonitorProfile: ?PWSTR, ccMonitorProfile: u32, pPrinterProfile: ?PWSTR, ccPrinterProfile: u32, pTargetProfile: ?PWSTR, ccTargetProfile: u32, lpfnHook: ?DLGPROC, lParam: LPARAM, lpfnApplyCallback: ?PCMSCALLBACKW, lParamApplyCallback: LPARAM, }; pub const COLORMATCHSETUPA = extern struct { dwSize: u32, dwVersion: u32, dwFlags: u32, hwndOwner: ?HWND, pSourceName: ?[*:0]const u8, pDisplayName: ?[*:0]const u8, pPrinterName: ?[*:0]const u8, dwRenderIntent: u32, dwProofingIntent: u32, pMonitorProfile: ?PSTR, ccMonitorProfile: u32, pPrinterProfile: ?PSTR, ccPrinterProfile: u32, pTargetProfile: ?PSTR, ccTargetProfile: u32, lpfnHook: ?DLGPROC, lParam: LPARAM, lpfnApplyCallback: ?PCMSCALLBACKA, lParamApplyCallback: LPARAM, }; pub const WCS_DEVICE_VCGT_CAPABILITIES = extern struct { Size: u32, SupportsVcgt: BOOL, }; pub const WCS_DEVICE_MHC2_CAPABILITIES = extern struct { Size: u32, SupportsMhc2: BOOL, RegammaLutEntryCount: u32, CscXyzMatrixRows: u32, CscXyzMatrixColumns: u32, }; pub const WCS_DEVICE_CAPABILITIES_TYPE = enum(i32) { VideoCardGammaTable = 1, MicrosoftHardwareColorV2 = 2, }; pub const VideoCardGammaTable = WCS_DEVICE_CAPABILITIES_TYPE.VideoCardGammaTable; pub const MicrosoftHardwareColorV2 = WCS_DEVICE_CAPABILITIES_TYPE.MicrosoftHardwareColorV2; //-------------------------------------------------------------------------------- // Section: Functions (121) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SetICMMode( hdc: ?HDC, mode: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CheckColorsInGamut( hdc: ?HDC, lpRGBTriple: [*]RGBTRIPLE, // TODO: what to do with BytesParamIndex 3? dlpBuffer: ?*anyopaque, nCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetColorSpace( hdc: ?HDC, ) callconv(@import("std").os.windows.WINAPI) ?HCOLORSPACE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetLogColorSpaceA( hColorSpace: ?HCOLORSPACE, // TODO: what to do with BytesParamIndex 2? lpBuffer: ?*LOGCOLORSPACEA, nSize: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetLogColorSpaceW( hColorSpace: ?HCOLORSPACE, // TODO: what to do with BytesParamIndex 2? lpBuffer: ?*LOGCOLORSPACEW, nSize: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CreateColorSpaceA( lplcs: ?*LOGCOLORSPACEA, ) callconv(@import("std").os.windows.WINAPI) ?HCOLORSPACE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CreateColorSpaceW( lplcs: ?*LOGCOLORSPACEW, ) callconv(@import("std").os.windows.WINAPI) ?HCOLORSPACE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SetColorSpace( hdc: ?HDC, hcs: ?HCOLORSPACE, ) callconv(@import("std").os.windows.WINAPI) ?HCOLORSPACE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn DeleteColorSpace( hcs: ?HCOLORSPACE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetICMProfileA( hdc: ?HDC, pBufSize: ?*u32, pszFilename: ?[*:0]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetICMProfileW( hdc: ?HDC, pBufSize: ?*u32, pszFilename: ?[*:0]u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SetICMProfileA( hdc: ?HDC, lpFileName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SetICMProfileW( hdc: ?HDC, lpFileName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn GetDeviceGammaRamp( hdc: ?HDC, lpRamp: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn SetDeviceGammaRamp( hdc: ?HDC, lpRamp: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn ColorMatchToTarget( hdc: ?HDC, hdcTarget: ?HDC, action: COLOR_MATCH_TO_TARGET_ACTION, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EnumICMProfilesA( hdc: ?HDC, proc: ?ICMENUMPROCA, param2: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EnumICMProfilesW( hdc: ?HDC, proc: ?ICMENUMPROCW, param2: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn UpdateICMRegKeyA( reserved: u32, lpszCMID: ?PSTR, lpszFileName: ?PSTR, command: ICM_COMMAND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn UpdateICMRegKeyW( reserved: u32, lpszCMID: ?PWSTR, lpszFileName: ?PWSTR, command: ICM_COMMAND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn ColorCorrectPalette( hdc: ?HDC, hPal: ?HPALETTE, deFirst: u32, num: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn OpenColorProfileA( pProfile: ?*PROFILE, dwDesiredAccess: u32, dwShareMode: u32, dwCreationMode: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn OpenColorProfileW( pProfile: ?*PROFILE, dwDesiredAccess: u32, dwShareMode: u32, dwCreationMode: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn CloseColorProfile( hProfile: isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetColorProfileFromHandle( hProfile: isize, // TODO: what to do with BytesParamIndex 2? pProfile: ?*u8, pcbProfile: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn IsColorProfileValid( hProfile: isize, pbValid: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn CreateProfileFromLogColorSpaceA( pLogColorSpace: ?*LOGCOLORSPACEA, pProfile: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn CreateProfileFromLogColorSpaceW( pLogColorSpace: ?*LOGCOLORSPACEW, pProfile: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetCountColorProfileElements( hProfile: isize, pnElementCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetColorProfileHeader( hProfile: isize, pHeader: ?*PROFILEHEADER, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetColorProfileElementTag( hProfile: isize, dwIndex: u32, pTag: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn IsColorProfileTagPresent( hProfile: isize, tag: u32, pbPresent: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetColorProfileElement( hProfile: isize, tag: u32, dwOffset: u32, pcbElement: ?*u32, // TODO: what to do with BytesParamIndex 3? pElement: ?*anyopaque, pbReference: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SetColorProfileHeader( hProfile: isize, pHeader: ?*PROFILEHEADER, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SetColorProfileElementSize( hProfile: isize, tagType: u32, pcbElement: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SetColorProfileElement( hProfile: isize, tag: u32, dwOffset: u32, pcbElement: ?*u32, pElement: [*]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SetColorProfileElementReference( hProfile: isize, newTag: u32, refTag: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetPS2ColorSpaceArray( hProfile: isize, dwIntent: u32, dwCSAType: u32, // TODO: what to do with BytesParamIndex 4? pPS2ColorSpaceArray: ?*u8, pcbPS2ColorSpaceArray: ?*u32, pbBinary: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetPS2ColorRenderingIntent( hProfile: isize, dwIntent: u32, // TODO: what to do with BytesParamIndex 3? pBuffer: ?*u8, pcbPS2ColorRenderingIntent: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetPS2ColorRenderingDictionary( hProfile: isize, dwIntent: u32, // TODO: what to do with BytesParamIndex 3? pPS2ColorRenderingDictionary: ?*u8, pcbPS2ColorRenderingDictionary: ?*u32, pbBinary: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetNamedProfileInfo( hProfile: isize, pNamedProfileInfo: ?*NAMED_PROFILE_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn ConvertColorNameToIndex( hProfile: isize, paColorName: [*]?*i8, paIndex: [*]u32, dwCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn ConvertIndexToColorName( hProfile: isize, paIndex: [*]u32, paColorName: [*]?*i8, dwCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn CreateDeviceLinkProfile( hProfile: [*]isize, nProfiles: u32, padwIntent: [*]u32, nIntents: u32, dwFlags: u32, pProfileData: ?*?*u8, indexPreferredCMM: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn CreateColorTransformA( pLogColorSpace: ?*LOGCOLORSPACEA, hDestProfile: isize, hTargetProfile: isize, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn CreateColorTransformW( pLogColorSpace: ?*LOGCOLORSPACEW, hDestProfile: isize, hTargetProfile: isize, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn CreateMultiProfileTransform( pahProfiles: [*]isize, nProfiles: u32, padwIntent: [*]u32, nIntents: u32, dwFlags: u32, indexPreferredCMM: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn DeleteColorTransform( hxform: isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn TranslateBitmapBits( hColorTransform: isize, pSrcBits: ?*anyopaque, bmInput: BMFORMAT, dwWidth: u32, dwHeight: u32, dwInputStride: u32, pDestBits: ?*anyopaque, bmOutput: BMFORMAT, dwOutputStride: u32, pfnCallBack: ?LPBMCALLBACKFN, ulCallbackData: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn CheckBitmapBits( hColorTransform: isize, pSrcBits: ?*anyopaque, bmInput: BMFORMAT, dwWidth: u32, dwHeight: u32, dwStride: u32, paResult: ?*u8, pfnCallback: ?LPBMCALLBACKFN, lpCallbackData: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn TranslateColors( hColorTransform: isize, paInputColors: [*]COLOR, nColors: u32, ctInput: COLORTYPE, paOutputColors: [*]COLOR, ctOutput: COLORTYPE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn CheckColors( hColorTransform: isize, paInputColors: [*]COLOR, nColors: u32, ctInput: COLORTYPE, paResult: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetCMMInfo( hColorTransform: isize, param1: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "mscms" fn RegisterCMMA( pMachineName: ?[*:0]const u8, cmmID: u32, pCMMdll: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn RegisterCMMW( pMachineName: ?[*:0]const u16, cmmID: u32, pCMMdll: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn UnregisterCMMA( pMachineName: ?[*:0]const u8, cmmID: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn UnregisterCMMW( pMachineName: ?[*:0]const u16, cmmID: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SelectCMM( dwCMMType: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetColorDirectoryA( pMachineName: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 2? pBuffer: ?PSTR, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetColorDirectoryW( pMachineName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 2? pBuffer: ?PWSTR, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn InstallColorProfileA( pMachineName: ?[*:0]const u8, pProfileName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn InstallColorProfileW( pMachineName: ?[*:0]const u16, pProfileName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn UninstallColorProfileA( pMachineName: ?[*:0]const u8, pProfileName: ?[*:0]const u8, bDelete: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn UninstallColorProfileW( pMachineName: ?[*:0]const u16, pProfileName: ?[*:0]const u16, bDelete: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn EnumColorProfilesA( pMachineName: ?[*:0]const u8, pEnumRecord: ?*ENUMTYPEA, // TODO: what to do with BytesParamIndex 3? pEnumerationBuffer: ?*u8, pdwSizeOfEnumerationBuffer: ?*u32, pnProfiles: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn EnumColorProfilesW( pMachineName: ?[*:0]const u16, pEnumRecord: ?*ENUMTYPEW, // TODO: what to do with BytesParamIndex 3? pEnumerationBuffer: ?*u8, pdwSizeOfEnumerationBuffer: ?*u32, pnProfiles: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SetStandardColorSpaceProfileA( pMachineName: ?[*:0]const u8, dwProfileID: u32, pProfilename: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SetStandardColorSpaceProfileW( pMachineName: ?[*:0]const u16, dwProfileID: u32, pProfileName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetStandardColorSpaceProfileA( pMachineName: ?[*:0]const u8, dwSCS: u32, // TODO: what to do with BytesParamIndex 3? pBuffer: ?PSTR, pcbSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GetStandardColorSpaceProfileW( pMachineName: ?[*:0]const u16, dwSCS: u32, // TODO: what to do with BytesParamIndex 3? pBuffer: ?PWSTR, pcbSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn AssociateColorProfileWithDeviceA( pMachineName: ?[*:0]const u8, pProfileName: ?[*:0]const u8, pDeviceName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn AssociateColorProfileWithDeviceW( pMachineName: ?[*:0]const u16, pProfileName: ?[*:0]const u16, pDeviceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn DisassociateColorProfileFromDeviceA( pMachineName: ?[*:0]const u8, pProfileName: ?[*:0]const u8, pDeviceName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn DisassociateColorProfileFromDeviceW( pMachineName: ?[*:0]const u16, pProfileName: ?[*:0]const u16, pDeviceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICMUI" fn SetupColorMatchingW( pcms: ?*COLORMATCHSETUPW, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICMUI" fn SetupColorMatchingA( pcms: ?*COLORMATCHSETUPA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsAssociateColorProfileWithDevice( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pProfileName: ?[*:0]const u16, pDeviceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsDisassociateColorProfileFromDevice( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pProfileName: ?[*:0]const u16, pDeviceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsEnumColorProfilesSize( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pEnumRecord: ?*ENUMTYPEW, pdwSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsEnumColorProfiles( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pEnumRecord: ?*ENUMTYPEW, // TODO: what to do with BytesParamIndex 3? pBuffer: ?*u8, dwSize: u32, pnProfiles: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsGetDefaultColorProfileSize( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pDeviceName: ?[*:0]const u16, cptColorProfileType: COLORPROFILETYPE, cpstColorProfileSubType: COLORPROFILESUBTYPE, dwProfileID: u32, pcbProfileName: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsGetDefaultColorProfile( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pDeviceName: ?[*:0]const u16, cptColorProfileType: COLORPROFILETYPE, cpstColorProfileSubType: COLORPROFILESUBTYPE, dwProfileID: u32, cbProfileName: u32, // TODO: what to do with BytesParamIndex 5? pProfileName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsSetDefaultColorProfile( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pDeviceName: ?[*:0]const u16, cptColorProfileType: COLORPROFILETYPE, cpstColorProfileSubType: COLORPROFILESUBTYPE, dwProfileID: u32, pProfileName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsSetDefaultRenderingIntent( scope: WCS_PROFILE_MANAGEMENT_SCOPE, dwRenderingIntent: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsGetDefaultRenderingIntent( scope: WCS_PROFILE_MANAGEMENT_SCOPE, pdwRenderingIntent: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsGetUsePerUserProfiles( pDeviceName: ?[*:0]const u16, dwDeviceClass: u32, pUsePerUserProfiles: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsSetUsePerUserProfiles( pDeviceName: ?[*:0]const u16, dwDeviceClass: u32, usePerUserProfiles: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsTranslateColors( hColorTransform: isize, nColors: u32, nInputChannels: u32, cdtInput: COLORDATATYPE, cbInput: u32, // TODO: what to do with BytesParamIndex 4? pInputData: ?*anyopaque, nOutputChannels: u32, cdtOutput: COLORDATATYPE, cbOutput: u32, // TODO: what to do with BytesParamIndex 8? pOutputData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsCheckColors( hColorTransform: isize, nColors: u32, nInputChannels: u32, cdtInput: COLORDATATYPE, cbInput: u32, // TODO: what to do with BytesParamIndex 4? pInputData: ?*anyopaque, paResult: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMCheckColors( hcmTransform: isize, lpaInputColors: [*]COLOR, nColors: u32, ctInput: COLORTYPE, lpaResult: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMCheckRGBs( hcmTransform: isize, lpSrcBits: ?*anyopaque, bmInput: BMFORMAT, dwWidth: u32, dwHeight: u32, dwStride: u32, lpaResult: ?*u8, pfnCallback: ?LPBMCALLBACKFN, ulCallbackData: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMConvertColorNameToIndex( hProfile: isize, paColorName: [*]?*i8, paIndex: [*]u32, dwCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMConvertIndexToColorName( hProfile: isize, paIndex: [*]u32, paColorName: [*]?*i8, dwCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMCreateDeviceLinkProfile( pahProfiles: [*]isize, nProfiles: u32, padwIntents: [*]u32, nIntents: u32, dwFlags: u32, lpProfileData: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMCreateMultiProfileTransform( pahProfiles: [*]isize, nProfiles: u32, padwIntents: [*]u32, nIntents: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "ICM32" fn CMCreateProfileW( lpColorSpace: ?*LOGCOLORSPACEW, lpProfileData: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMCreateTransform( lpColorSpace: ?*LOGCOLORSPACEA, lpDevCharacter: ?*anyopaque, lpTargetDevCharacter: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "ICM32" fn CMCreateTransformW( lpColorSpace: ?*LOGCOLORSPACEW, lpDevCharacter: ?*anyopaque, lpTargetDevCharacter: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "ICM32" fn CMCreateTransformExt( lpColorSpace: ?*LOGCOLORSPACEA, lpDevCharacter: ?*anyopaque, lpTargetDevCharacter: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "ICM32" fn CMCheckColorsInGamut( hcmTransform: isize, lpaRGBTriple: [*]RGBTRIPLE, // TODO: what to do with BytesParamIndex 3? lpaResult: ?*u8, nCount: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMCreateProfile( lpColorSpace: ?*LOGCOLORSPACEA, lpProfileData: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMTranslateRGB( hcmTransform: isize, ColorRef: u32, lpColorRef: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMTranslateRGBs( hcmTransform: isize, lpSrcBits: ?*anyopaque, bmInput: BMFORMAT, dwWidth: u32, dwHeight: u32, dwStride: u32, lpDestBits: ?*anyopaque, bmOutput: BMFORMAT, dwTranslateDirection: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMCreateTransformExtW( lpColorSpace: ?*LOGCOLORSPACEW, lpDevCharacter: ?*anyopaque, lpTargetDevCharacter: ?*anyopaque, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "ICM32" fn CMDeleteTransform( hcmTransform: isize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMGetInfo( dwInfo: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "ICM32" fn CMGetNamedProfileInfo( hProfile: isize, pNamedProfileInfo: ?*NAMED_PROFILE_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMIsProfileValid( hProfile: isize, lpbValid: ?*i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMTranslateColors( hcmTransform: isize, lpaInputColors: [*]COLOR, nColors: u32, ctInput: COLORTYPE, lpaOutputColors: [*]COLOR, ctOutput: COLORTYPE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "ICM32" fn CMTranslateRGBsExt( hcmTransform: isize, lpSrcBits: ?*anyopaque, bmInput: BMFORMAT, dwWidth: u32, dwHeight: u32, dwInputStride: u32, lpDestBits: ?*anyopaque, bmOutput: BMFORMAT, dwOutputStride: u32, lpfnCallback: ?LPBMCALLBACKFN, ulCallbackData: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsOpenColorProfileA( pCDMPProfile: ?*PROFILE, pCAMPProfile: ?*PROFILE, pGMMPProfile: ?*PROFILE, dwDesireAccess: u32, dwShareMode: u32, dwCreationMode: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn WcsOpenColorProfileW( pCDMPProfile: ?*PROFILE, pCAMPProfile: ?*PROFILE, pGMMPProfile: ?*PROFILE, dwDesireAccess: u32, dwShareMode: u32, dwCreationMode: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn WcsCreateIccProfile( hWcsProfile: isize, dwOptions: u32, ) callconv(@import("std").os.windows.WINAPI) isize; pub extern "mscms" fn WcsGetCalibrationManagementState( pbIsEnabled: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn WcsSetCalibrationManagementState( bIsEnabled: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn ColorProfileAddDisplayAssociation( scope: WCS_PROFILE_MANAGEMENT_SCOPE, profileName: ?[*:0]const u16, targetAdapterID: LUID, sourceID: u32, setAsDefault: BOOL, associateAsAdvancedColor: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "mscms" fn ColorProfileRemoveDisplayAssociation( scope: WCS_PROFILE_MANAGEMENT_SCOPE, profileName: ?[*:0]const u16, targetAdapterID: LUID, sourceID: u32, dissociateAdvancedColor: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "mscms" fn ColorProfileSetDisplayDefaultAssociation( scope: WCS_PROFILE_MANAGEMENT_SCOPE, profileName: ?[*:0]const u16, profileType: COLORPROFILETYPE, profileSubType: COLORPROFILESUBTYPE, targetAdapterID: LUID, sourceID: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "mscms" fn ColorProfileGetDisplayList( scope: WCS_PROFILE_MANAGEMENT_SCOPE, targetAdapterID: LUID, sourceID: u32, profileList: ?*?*?PWSTR, profileCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "mscms" fn ColorProfileGetDisplayDefault( scope: WCS_PROFILE_MANAGEMENT_SCOPE, targetAdapterID: LUID, sourceID: u32, profileType: COLORPROFILETYPE, profileSubType: COLORPROFILESUBTYPE, profileName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "mscms" fn ColorProfileGetDisplayUserScope( targetAdapterID: LUID, sourceID: u32, scope: ?*WCS_PROFILE_MANAGEMENT_SCOPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (26) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const LOGCOLORSPACE = thismodule.LOGCOLORSPACEA; pub const ICMENUMPROC = thismodule.ICMENUMPROCA; pub const ENUMTYPE = thismodule.ENUMTYPEA; pub const PCMSCALLBACK = thismodule.PCMSCALLBACKA; pub const COLORMATCHSETUP = thismodule.COLORMATCHSETUPA; pub const GetLogColorSpace = thismodule.GetLogColorSpaceA; pub const CreateColorSpace = thismodule.CreateColorSpaceA; pub const GetICMProfile = thismodule.GetICMProfileA; pub const SetICMProfile = thismodule.SetICMProfileA; pub const EnumICMProfiles = thismodule.EnumICMProfilesA; pub const UpdateICMRegKey = thismodule.UpdateICMRegKeyA; pub const OpenColorProfile = thismodule.OpenColorProfileA; pub const CreateProfileFromLogColorSpace = thismodule.CreateProfileFromLogColorSpaceA; pub const CreateColorTransform = thismodule.CreateColorTransformA; pub const RegisterCMM = thismodule.RegisterCMMA; pub const UnregisterCMM = thismodule.UnregisterCMMA; pub const GetColorDirectory = thismodule.GetColorDirectoryA; pub const InstallColorProfile = thismodule.InstallColorProfileA; pub const UninstallColorProfile = thismodule.UninstallColorProfileA; pub const EnumColorProfiles = thismodule.EnumColorProfilesA; pub const SetStandardColorSpaceProfile = thismodule.SetStandardColorSpaceProfileA; pub const GetStandardColorSpaceProfile = thismodule.GetStandardColorSpaceProfileA; pub const AssociateColorProfileWithDevice = thismodule.AssociateColorProfileWithDeviceA; pub const DisassociateColorProfileFromDevice = thismodule.DisassociateColorProfileFromDeviceA; pub const SetupColorMatching = thismodule.SetupColorMatchingA; pub const WcsOpenColorProfile = thismodule.WcsOpenColorProfileA; }, .wide => struct { pub const LOGCOLORSPACE = thismodule.LOGCOLORSPACEW; pub const ICMENUMPROC = thismodule.ICMENUMPROCW; pub const ENUMTYPE = thismodule.ENUMTYPEW; pub const PCMSCALLBACK = thismodule.PCMSCALLBACKW; pub const COLORMATCHSETUP = thismodule.COLORMATCHSETUPW; pub const GetLogColorSpace = thismodule.GetLogColorSpaceW; pub const CreateColorSpace = thismodule.CreateColorSpaceW; pub const GetICMProfile = thismodule.GetICMProfileW; pub const SetICMProfile = thismodule.SetICMProfileW; pub const EnumICMProfiles = thismodule.EnumICMProfilesW; pub const UpdateICMRegKey = thismodule.UpdateICMRegKeyW; pub const OpenColorProfile = thismodule.OpenColorProfileW; pub const CreateProfileFromLogColorSpace = thismodule.CreateProfileFromLogColorSpaceW; pub const CreateColorTransform = thismodule.CreateColorTransformW; pub const RegisterCMM = thismodule.RegisterCMMW; pub const UnregisterCMM = thismodule.UnregisterCMMW; pub const GetColorDirectory = thismodule.GetColorDirectoryW; pub const InstallColorProfile = thismodule.InstallColorProfileW; pub const UninstallColorProfile = thismodule.UninstallColorProfileW; pub const EnumColorProfiles = thismodule.EnumColorProfilesW; pub const SetStandardColorSpaceProfile = thismodule.SetStandardColorSpaceProfileW; pub const GetStandardColorSpaceProfile = thismodule.GetStandardColorSpaceProfileW; pub const AssociateColorProfileWithDevice = thismodule.AssociateColorProfileWithDeviceW; pub const DisassociateColorProfileFromDevice = thismodule.DisassociateColorProfileFromDeviceW; pub const SetupColorMatching = thismodule.SetupColorMatchingW; pub const WcsOpenColorProfile = thismodule.WcsOpenColorProfileW; }, .unspecified => if (@import("builtin").is_test) struct { pub const LOGCOLORSPACE = *opaque{}; pub const ICMENUMPROC = *opaque{}; pub const ENUMTYPE = *opaque{}; pub const PCMSCALLBACK = *opaque{}; pub const COLORMATCHSETUP = *opaque{}; pub const GetLogColorSpace = *opaque{}; pub const CreateColorSpace = *opaque{}; pub const GetICMProfile = *opaque{}; pub const SetICMProfile = *opaque{}; pub const EnumICMProfiles = *opaque{}; pub const UpdateICMRegKey = *opaque{}; pub const OpenColorProfile = *opaque{}; pub const CreateProfileFromLogColorSpace = *opaque{}; pub const CreateColorTransform = *opaque{}; pub const RegisterCMM = *opaque{}; pub const UnregisterCMM = *opaque{}; pub const GetColorDirectory = *opaque{}; pub const InstallColorProfile = *opaque{}; pub const UninstallColorProfile = *opaque{}; pub const EnumColorProfiles = *opaque{}; pub const SetStandardColorSpaceProfile = *opaque{}; pub const GetStandardColorSpaceProfile = *opaque{}; pub const AssociateColorProfileWithDevice = *opaque{}; pub const DisassociateColorProfileFromDevice = *opaque{}; pub const SetupColorMatching = *opaque{}; pub const WcsOpenColorProfile = *opaque{}; } else struct { pub const LOGCOLORSPACE = @compileError("'LOGCOLORSPACE' requires that UNICODE be set to true or false in the root module"); pub const ICMENUMPROC = @compileError("'ICMENUMPROC' requires that UNICODE be set to true or false in the root module"); pub const ENUMTYPE = @compileError("'ENUMTYPE' requires that UNICODE be set to true or false in the root module"); pub const PCMSCALLBACK = @compileError("'PCMSCALLBACK' requires that UNICODE be set to true or false in the root module"); pub const COLORMATCHSETUP = @compileError("'COLORMATCHSETUP' requires that UNICODE be set to true or false in the root module"); pub const GetLogColorSpace = @compileError("'GetLogColorSpace' requires that UNICODE be set to true or false in the root module"); pub const CreateColorSpace = @compileError("'CreateColorSpace' requires that UNICODE be set to true or false in the root module"); pub const GetICMProfile = @compileError("'GetICMProfile' requires that UNICODE be set to true or false in the root module"); pub const SetICMProfile = @compileError("'SetICMProfile' requires that UNICODE be set to true or false in the root module"); pub const EnumICMProfiles = @compileError("'EnumICMProfiles' requires that UNICODE be set to true or false in the root module"); pub const UpdateICMRegKey = @compileError("'UpdateICMRegKey' requires that UNICODE be set to true or false in the root module"); pub const OpenColorProfile = @compileError("'OpenColorProfile' requires that UNICODE be set to true or false in the root module"); pub const CreateProfileFromLogColorSpace = @compileError("'CreateProfileFromLogColorSpace' requires that UNICODE be set to true or false in the root module"); pub const CreateColorTransform = @compileError("'CreateColorTransform' requires that UNICODE be set to true or false in the root module"); pub const RegisterCMM = @compileError("'RegisterCMM' requires that UNICODE be set to true or false in the root module"); pub const UnregisterCMM = @compileError("'UnregisterCMM' requires that UNICODE be set to true or false in the root module"); pub const GetColorDirectory = @compileError("'GetColorDirectory' requires that UNICODE be set to true or false in the root module"); pub const InstallColorProfile = @compileError("'InstallColorProfile' requires that UNICODE be set to true or false in the root module"); pub const UninstallColorProfile = @compileError("'UninstallColorProfile' requires that UNICODE be set to true or false in the root module"); pub const EnumColorProfiles = @compileError("'EnumColorProfiles' requires that UNICODE be set to true or false in the root module"); pub const SetStandardColorSpaceProfile = @compileError("'SetStandardColorSpaceProfile' requires that UNICODE be set to true or false in the root module"); pub const GetStandardColorSpaceProfile = @compileError("'GetStandardColorSpaceProfile' requires that UNICODE be set to true or false in the root module"); pub const AssociateColorProfileWithDevice = @compileError("'AssociateColorProfileWithDevice' requires that UNICODE be set to true or false in the root module"); pub const DisassociateColorProfileFromDevice = @compileError("'DisassociateColorProfileFromDevice' requires that UNICODE be set to true or false in the root module"); pub const SetupColorMatching = @compileError("'SetupColorMatching' requires that UNICODE be set to true or false in the root module"); pub const WcsOpenColorProfile = @compileError("'WcsOpenColorProfile' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (18) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const CHAR = @import("../foundation.zig").CHAR; const CIEXYZ = @import("../graphics/gdi.zig").CIEXYZ; const CIEXYZTRIPLE = @import("../graphics/gdi.zig").CIEXYZTRIPLE; const DLGPROC = @import("../ui/windows_and_messaging.zig").DLGPROC; const EMR = @import("../graphics/gdi.zig").EMR; const HDC = @import("../graphics/gdi.zig").HDC; const HPALETTE = @import("../graphics/gdi.zig").HPALETTE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IUnknown = @import("../system/com.zig").IUnknown; const LPARAM = @import("../foundation.zig").LPARAM; const LUID = @import("../foundation.zig").LUID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const RGBTRIPLE = @import("../graphics/gdi.zig").RGBTRIPLE; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "ICMENUMPROCA")) { _ = ICMENUMPROCA; } if (@hasDecl(@This(), "ICMENUMPROCW")) { _ = ICMENUMPROCW; } if (@hasDecl(@This(), "LPBMCALLBACKFN")) { _ = LPBMCALLBACKFN; } if (@hasDecl(@This(), "PCMSCALLBACKW")) { _ = PCMSCALLBACKW; } if (@hasDecl(@This(), "PCMSCALLBACKA")) { _ = PCMSCALLBACKA; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/ui/color_system.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log.scoped(.clock); const config = @import("../config.zig"); const clock_offset_tolerance_max: u64 = config.clock_offset_tolerance_max_ms * std.time.ns_per_ms; const epoch_max: u64 = config.clock_epoch_max_ms * std.time.ns_per_ms; const window_min: u64 = config.clock_synchronization_window_min_ms * std.time.ns_per_ms; const window_max: u64 = config.clock_synchronization_window_max_ms * std.time.ns_per_ms; const Marzullo = @import("../marzullo.zig").Marzullo; const Time = @import("../time.zig").Time; const Sample = struct { /// The relative difference between our wall clock reading and that of the remote clock source. clock_offset: i64, one_way_delay: u64, }; const Epoch = struct { const Self = @This(); /// The best clock offset sample per remote clock source (with minimum one way delay) collected /// over the course of a window period of several seconds. sources: []?Sample, /// The total number of samples learned while synchronizing this epoch. samples: usize, /// The monotonic clock timestamp when this epoch began. We use this to measure elapsed time. monotonic: u64, /// The wall clock timestamp when this epoch began. We add the elapsed monotonic time to this /// plus the synchronized clock offset to arrive at a synchronized realtime timestamp. We /// capture this realtime when starting the epoch, before we take any samples, to guard against /// any jumps in the system's realtime clock from impacting our measurements. realtime: i64, /// Once we have enough source clock offset samples in agreement, the epoch is synchronized. /// We then have lower and upper bounds on the true cluster time, and can install this epoch for /// subsequent clock readings. This epoch is then valid for several seconds, while clock drift /// has not had enough time to accumulate into any significant clock skew, and while we collect /// samples for the next epoch to refresh and replace this one. synchronized: ?Marzullo.Interval, /// A guard to prevent synchronizing too often without having learned any new samples. learned: bool = false, fn elapsed(self: *Self, clock: *Clock) u64 { return clock.monotonic() - self.monotonic; } fn reset(self: *Self, clock: *Clock) void { std.mem.set(?Sample, self.sources, null); // A replica always has zero clock offset and network delay to its own system time reading: self.sources[clock.replica] = Sample{ .clock_offset = 0, .one_way_delay = 0, }; self.samples = 1; self.monotonic = clock.monotonic(); self.realtime = clock.realtime(); self.synchronized = null; self.learned = false; } fn sources_sampled(self: *Self) usize { var count: usize = 0; for (self.sources) |sampled| { if (sampled != null) count += 1; } return count; } }; pub const Clock = struct { const Self = @This(); allocator: *std.mem.Allocator, /// The index of the replica using this clock to provide synchronized time. replica: u8, /// The underlying time source for this clock (system time or deterministic time). time: *Time, /// An epoch from which the clock can read synchronized clock timestamps within safe bounds. /// At least `config.clock_synchronization_window_min_ms` is needed for this to be ready to use. epoch: Epoch, /// The next epoch (collecting samples and being synchronized) to replace the current epoch. window: Epoch, /// A static allocation to convert window samples into tuple bounds for Marzullo's algorithm. marzullo_tuples: []Marzullo.Tuple, /// A kill switch to revert to unsynchronized realtime. synchronization_disabled: bool, pub fn init( allocator: *std.mem.Allocator, /// The size of the cluster, i.e. the number of clock sources (including this replica). replica_count: u8, replica: u8, time: *Time, ) !Clock { assert(replica_count > 0); assert(replica < replica_count); var epoch: Epoch = undefined; epoch.sources = try allocator.alloc(?Sample, replica_count); errdefer allocator.free(epoch.sources); var window: Epoch = undefined; window.sources = try allocator.alloc(?Sample, replica_count); errdefer allocator.free(window.sources); // There are two Marzullo tuple bounds (lower and upper) per source clock offset sample: var marzullo_tuples = try allocator.alloc(Marzullo.Tuple, replica_count * 2); errdefer allocator.free(marzullo_tuples); var self = Clock{ .allocator = allocator, .replica = replica, .time = time, .epoch = epoch, .window = window, .marzullo_tuples = marzullo_tuples, .synchronization_disabled = replica_count == 1, // A cluster of one cannot synchronize. }; // Reset the current epoch to be unsynchronized, self.epoch.reset(&self); // and open a new epoch window to start collecting samples... self.window.reset(&self); return self; } /// Called by `Replica.on_pong()` with: /// * the index of the `replica` that has replied to our ping with a pong, /// * our monotonic timestamp `m0` embedded in the ping we sent, carried over into this pong, /// * the remote replica's `realtime()` timestamp `t1`, and /// * our monotonic timestamp `m2` as captured by our `Replica.on_pong()` handler. pub fn learn(self: *Self, replica: u8, m0: u64, t1: i64, m2: u64) void { if (self.synchronization_disabled) return; // A network routing fault must have replayed one of our outbound messages back against us: if (replica == self.replica) return; // Our m0 and m2 readings should always be monotonically increasing. // This condition should never be true. Reject this as a bad sample: if (m0 >= m2) return; // We may receive delayed packets after a reboot, in which case m0/m2 may be invalid: if (m0 < self.window.monotonic) return; if (m2 < self.window.monotonic) return; const elapsed: u64 = m2 - self.window.monotonic; if (elapsed > window_max) return; const round_trip_time: u64 = m2 - m0; const one_way_delay: u64 = round_trip_time / 2; const t2: i64 = self.window.realtime + @intCast(i64, elapsed); const clock_offset: i64 = t1 + @intCast(i64, one_way_delay) - t2; const asymmetric_delay = self.estimate_asymmetric_delay( replica, one_way_delay, clock_offset, ); const clock_offset_corrected = clock_offset + asymmetric_delay; log.debug("learn: replica={} m0={} t1={} m2={} t2={} one_way_delay={} " ++ "asymmetric_delay={} clock_offset={}", .{ replica, m0, t1, m2, t2, one_way_delay, asymmetric_delay, clock_offset_corrected, }); // The less network delay, the more likely we have an accurante clock offset measurement: self.window.sources[replica] = minimum_one_way_delay(self.window.sources[replica], Sample{ .clock_offset = clock_offset_corrected, .one_way_delay = one_way_delay, }); self.window.samples += 1; // We decouple calls to `synchronize()` so that it's not triggered by these network events. // Otherwise, excessive duplicate network packets would burn the CPU. self.window.learned = true; } /// Called by `Replica.on_ping_timeout()` to provide `m0` when we decide to send a ping. /// Called by `Replica.on_pong()` to provide `m2` when we receive a pong. pub fn monotonic(self: *Self) u64 { return self.time.monotonic(); } /// Called by `Replica.on_ping()` when responding to a ping with a pong. /// This should never be used by the state machine, only for measuring clock offsets. pub fn realtime(self: *Self) i64 { return self.time.realtime(); } /// Called by `StateMachine.prepare_timestamp()` when the leader wants to timestamp a batch. /// If the leader's clock is not synchronized with the cluster, it must wait until it is. /// Returns the system time clamped to be within our synchronized lower and upper bounds. /// This is complementary to NTP and allows clusters with very accurate time to make use of it, /// while providing guard rails for when NTP is partitioned or unable to correct quickly enough. pub fn realtime_synchronized(self: *Self) ?i64 { if (self.synchronization_disabled) { return self.realtime(); } else if (self.epoch.synchronized) |interval| { const elapsed = @intCast(i64, self.epoch.elapsed(self)); return std.math.clamp( self.realtime(), self.epoch.realtime + elapsed + interval.lower_bound, self.epoch.realtime + elapsed + interval.upper_bound, ); } else { return null; } } pub fn tick(self: *Self) void { self.time.tick(); if (self.synchronization_disabled) return; self.synchronize(); // Expire the current epoch if successive windows failed to synchronize: // Gradual clock drift prevents us from using an epoch for more than a few tens of seconds. if (self.epoch.elapsed(self) >= epoch_max) { log.alert("no agreement on cluster time (partitioned or too many clock faults)", .{}); self.epoch.reset(self); } } /// Estimates the asymmetric delay for a sample compared to the previous window, according to /// Algorithm 1 from Section 4.2, "A System for Clock Synchronization in an Internet of Things". fn estimate_asymmetric_delay( self: *Self, replica: u8, one_way_delay: u64, clock_offset: i64, ) i64 { const error_margin = 10 * std.time.ns_per_ms; if (self.epoch.sources[replica]) |epoch| { if (one_way_delay <= epoch.one_way_delay) { return 0; } else if (clock_offset > epoch.clock_offset + error_margin) { // The asymmetric error is on the forward network path. return 0 - @intCast(i64, one_way_delay - epoch.one_way_delay); } else if (clock_offset < epoch.clock_offset - error_margin) { // The asymmetric error is on the reverse network path. return 0 + @intCast(i64, one_way_delay - epoch.one_way_delay); } else { return 0; } } else { return 0; } } fn synchronize(self: *Self) void { assert(self.window.synchronized == null); // Wait until the window has enough accurate samples: const elapsed = self.window.elapsed(self); if (elapsed < window_min) return; if (elapsed >= window_max) { // We took too long to synchronize the window, expire stale samples... const sources_sampled = self.window.sources_sampled(); if (sources_sampled <= @divTrunc(self.window.sources.len, 2)) { log.crit("synchronization window failed, partitioned (sources={} samples={})", .{ sources_sampled, self.window.samples, }); } else { log.crit("synchronization window failed, no agreement (sources={} samples={})", .{ sources_sampled, self.window.samples, }); } self.window.reset(self); return; } if (!self.window.learned) return; // Do not reset `learned` any earlier than this (before we have attempted to synchronize). self.window.learned = false; // Starting with the most clock offset tolerance, while we have a majority, find the best // smallest interval with the least clock offset tolerance, reducing tolerance at each step: var tolerance: u64 = clock_offset_tolerance_max; var terminate = false; var rounds: usize = 0; // Do at least one round if tolerance=0 and cap the number of rounds to avoid runaway loops. while (!terminate and rounds < 64) : (tolerance /= 2) { if (tolerance == 0) terminate = true; rounds += 1; const interval = Marzullo.smallest_interval(self.window_tuples(tolerance)); const majority = interval.sources_true > @divTrunc(self.window.sources.len, 2); if (!majority) break; // The new interval may reduce the number of `sources_true` while also decreasing error. // In other words, provided we maintain a majority, we prefer tighter tolerance bounds. self.window.synchronized = interval; } // Wait for more accurate samples or until we timeout the window for lack of majority: if (self.window.synchronized == null) return; var new_window = self.epoch; new_window.reset(self); self.epoch = self.window; self.window = new_window; self.after_synchronization(); } fn after_synchronization(self: *Self) void { const new_interval = self.epoch.synchronized.?; log.info("synchronized: truechimers={}/{} clock_offset={}..{} accuracy={}", .{ new_interval.sources_true, self.epoch.sources.len, fmtDurationSigned(new_interval.lower_bound), fmtDurationSigned(new_interval.upper_bound), fmtDurationSigned(new_interval.upper_bound - new_interval.lower_bound), }); const elapsed = @intCast(i64, self.epoch.elapsed(self)); const system = self.realtime(); const lower = self.epoch.realtime + elapsed + new_interval.lower_bound; const upper = self.epoch.realtime + elapsed + new_interval.upper_bound; const cluster = std.math.clamp(system, lower, upper); if (system == cluster) { log.info("system time is within cluster time", .{}); } else if (system < lower) { const delta = lower - system; if (delta < std.time.ns_per_ms) { log.info("system time is {} behind", .{fmtDurationSigned(delta)}); } else { log.err("system time is {} behind, clamping system time to cluster time", .{ fmtDurationSigned(delta), }); } } else { const delta = system - upper; if (delta < std.time.ns_per_ms) { log.info("system time is {} ahead", .{fmtDurationSigned(delta)}); } else { log.err("system time is {} ahead, clamping system time to cluster time", .{ fmtDurationSigned(delta), }); } } } fn window_tuples(self: *Self, tolerance: u64) []Marzullo.Tuple { assert(self.window.sources[self.replica].?.clock_offset == 0); assert(self.window.sources[self.replica].?.one_way_delay == 0); var count: usize = 0; for (self.window.sources) |sampled, source| { if (sampled) |sample| { self.marzullo_tuples[count] = Marzullo.Tuple{ .source = @intCast(u8, source), .offset = sample.clock_offset - @intCast(i64, sample.one_way_delay + tolerance), .bound = .lower, }; count += 1; self.marzullo_tuples[count] = Marzullo.Tuple{ .source = @intCast(u8, source), .offset = sample.clock_offset + @intCast(i64, sample.one_way_delay + tolerance), .bound = .upper, }; count += 1; } } return self.marzullo_tuples[0..count]; } fn minimum_one_way_delay(a: ?Sample, b: ?Sample) ?Sample { if (a == null) return b; if (b == null) return a; if (a.?.one_way_delay < b.?.one_way_delay) return a; // Choose B if B's one way delay is less or the same (we assume B is the newer sample): return b; } }; /// Return a Formatter for a signed number of nanoseconds according to magnitude: /// [#y][#w][#d][#h][#m]#[.###][n|u|m]s pub fn fmtDurationSigned(ns: i64) std.fmt.Formatter(formatDurationSigned) { return .{ .data = ns }; } fn formatDurationSigned( ns: i64, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { if (ns < 0) { try writer.print("-{}", .{std.fmt.fmtDuration(@intCast(u64, -ns))}); } else { try writer.print("{}", .{std.fmt.fmtDuration(@intCast(u64, ns))}); } } // TODO Use tracing analysis to test a simulated trace, comparing against known values for accuracy.
src/vr/clock.zig
const std = @import("std"); const assert = std.debug.assert; const print = std.debug.print; const util = @import("util.zig"); const data = @embedFile("../data/day02.txt"); const Str = []const u8; fn readLineNum(input: Str, idx: *usize) !u8 { var start_idx: ?usize = null; while (idx.* < input.len) : (idx.* += 1) { switch (input[idx.*]) { ' ' => { start_idx = idx.* + 1; }, '\n' => break, else => continue, } } assert(start_idx != null); return std.fmt.parseUnsigned(u8, input[start_idx.?..idx.*], 10); } fn part1(input: Str) !u32 { var depth: u32 = 0; // assuming depth can't go negative var distance: u32 = 0; // Let's use a quicker parsing method, directly stepping through chars. var i: usize = 0; while (i < input.len) : (i += 1) { const direction: enum { Forward, Down, Up } = switch (input[i]) { 'f' => .Forward, 'd' => .Down, 'u' => .Up, else => return error.UnexpectedChar, }; const num = try readLineNum(input, &i); switch (direction) { .Forward => { distance += num; }, .Down => { depth += num; }, .Up => { depth -= num; }, } } return depth * distance; } fn part2(input: Str) !u32 { var distance: u32 = 0; var aim: i32 = 0; var depth: i32 = 0; // Let's use a quicker parsing method, directly stepping through chars. var i: usize = 0; while (i < input.len) : (i += 1) { const direction: enum { Forward, Down, Up } = switch (input[i]) { 'f' => .Forward, 'd' => .Down, 'u' => .Up, else => return error.UnexpectedChar, }; const num = try readLineNum(input, &i); switch (direction) { .Forward => { distance += num; depth += aim * num; }, .Down => { aim += num; }, .Up => { aim -= num; }, } } return @intCast(u32, depth) * distance; } pub fn main() !void { try util.runPart(part1, data); print("\n", .{}); try util.runPart(part2, data); } test "2a" { const input = \\forward 5 \\down 5 \\forward 8 \\up 3 \\down 8 \\forward 2 ; try std.testing.expectEqual(@as(u32, 150), try part1(input)); } test "2b" { const input = \\forward 5 \\down 5 \\forward 8 \\up 3 \\down 8 \\forward 2 ; try std.testing.expectEqual(@as(u32, 900), try part2(input)); }
src/day02.zig
usingnamespace @import("bits.zig"); const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const windows = @import("../windows.zig"); const unexpectedError = windows.unexpectedError; const GetLastError = windows.kernel32.GetLastError; const SetLastError = windows.kernel32.SetLastError; fn selectSymbol(comptime function_static: anytype, function_dynamic: @TypeOf(function_static), comptime os: std.Target.Os.WindowsVersion) @TypeOf(function_static) { comptime { const sym_ok = builtin.Target.current.os.isAtLeast(.windows, os); if (sym_ok == true) return function_static; if (sym_ok == null) return function_dynamic; if (sym_ok == false) @compileError("Target OS range does not support function, at least " ++ @tagName(os) ++ " is required"); } } // === Messages === pub const WNDPROC = fn (hwnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT; pub const MSG = extern struct { hWnd: ?HWND, message: UINT, wParam: WPARAM, lParam: LPARAM, time: DWORD, pt: POINT, lPrivate: DWORD, }; pub const WM_NULL = 0x0000; pub const WM_CREATE = 0x0001; pub const WM_DESTROY = 0x0002; pub const WM_NCDESTROY = WM_DESTROY; pub const WM_MOVE = 0x0003; pub const WM_SIZE = 0x0005; pub const WM_ACTIVATE = 0x0006; pub const WM_SETFOCUS = 0x0007; pub const WM_KILLFOCUS = 0x0008; pub const WM_ENABLE = 0x000A; pub const WM_SETREDRAW = 0x000B; pub const WM_SETTEXT = 0x000C; pub const WM_GETTEXT = 0x000D; pub const WM_GETTEXTLENGTH = 0x000E; pub const WM_PAINT = 0x000F; pub const WM_CLOSE = 0x0010; pub const WM_QUIT = 0x0012; pub const WM_ERASEBKGND = 0x0014; pub const WM_SHOWWINDOW = 0x0018; pub const WM_CTLCOLOR = 0x0019; pub const WM_NEXTDLGCTL = 0x0028; pub const WM_DRAWITEM = 0x002B; pub const WM_MEASUREITEM = 0x002C; pub const WM_DELETEITEM = 0x002D; pub const WM_VKEYTOITEM = 0x002E; pub const WM_CHARTOITEM = 0x002F; pub const WM_SETFONT = 0x0030; pub const WM_GETFONT = 0x0031; pub const WM_COMPAREITEM = 0x0039; pub const WM_WINDOWPOSCHANGED = 0x0047; pub const WM_NOTIFY = 0x004E; pub const WM_NCCALCSIZE = 0x0083; pub const WM_NCHITTEST = 0x0084; pub const WM_NCPAINT = 0x0085; pub const WM_GETDLGCODE = 0x0087; pub const WM_NCMOUSEMOVE = 0x00A0; pub const WM_NCLBUTTONDOWN = 0x00A1; pub const WM_NCLBUTTONUP = 0x00A2; pub const WM_NCLBUTTONDBLCLK = 0x00A3; pub const WM_NCRBUTTONDOWN = 0x00A4; pub const WM_NCRBUTTONUP = 0x00A5; pub const WM_NCRBUTTONDBLCLK = 0x00A6; pub const WM_KEYFIRST = 0x0100; pub const WM_KEYDOWN = 0x0100; pub const WM_KEYUP = 0x0101; pub const WM_CHAR = 0x0102; pub const WM_DEADCHAR = 0x0103; pub const WM_SYSKEYDOWN = 0x0104; pub const WM_SYSKEYUP = 0x0105; pub const WM_SYSCHAR = 0x0106; pub const WM_SYSDEADCHAR = 0x0107; pub const WM_UNICHAR = 0x0109; pub const WM_KEYLAST = 0x0109; pub const WM_INITDIALOG = 0x0110; pub const WM_COMMAND = 0x0111; pub const WM_SYSCOMMAND = 0x0112; pub const WM_TIMER = 0x0113; pub const WM_HSCROLL = 0x0114; pub const WM_VSCROLL = 0x0115; pub const WM_ENTERIDLE = 0x0121; pub const WM_CTLCOLORMSGBOX = 0x0132; pub const WM_CTLCOLOREDIT = 0x0133; pub const WM_CTLCOLORLISTBOX = 0x0134; pub const WM_CTLCOLORBTN = 0x0135; pub const WM_CTLCOLORDLG = 0x0136; pub const WM_CTLCOLORSCROLLBAR = 0x0137; pub const WM_CTLCOLORSTATIC = 0x0138; pub const WM_MOUSEFIRST = 0x0200; pub const WM_MOUSEMOVE = 0x0200; pub const WM_LBUTTONDOWN = 0x0201; pub const WM_LBUTTONUP = 0x0202; pub const WM_LBUTTONDBLCLK = 0x0203; pub const WM_RBUTTONDOWN = 0x0204; pub const WM_RBUTTONUP = 0x0205; pub const WM_RBUTTONDBLCLK = 0x0206; pub const WM_MBUTTONDOWN = 0x0207; pub const WM_MBUTTONUP = 0x0208; pub const WM_MBUTTONDBLCLK = 0x0209; pub const WM_MOUSEWHEEL = 0x020A; pub const WM_MOUSELAST = 0x020A; pub const WM_HOTKEY = 0x0312; pub const WM_CARET_CREATE = 0x03E0; pub const WM_CARET_DESTROY = 0x03E1; pub const WM_CARET_BLINK = 0x03E2; pub const WM_FDINPUT = 0x03F0; pub const WM_FDOUTPUT = 0x03F1; pub const WM_FDEXCEPT = 0x03F2; pub const WM_USER = 0x0400; pub extern "user32" fn GetMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT) callconv(WINAPI) BOOL; pub fn getMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32) !void { const r = GetMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax); if (r == 0) return error.Quit; if (r != -1) return; switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn GetMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT) callconv(WINAPI) BOOL; pub var pfnGetMessageW: @TypeOf(GetMessageW) = undefined; pub fn getMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32) !void { const function = selectSymbol(GetMessageW, pfnGetMessageW, .win2k); const r = function(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax); if (r == 0) return error.Quit; if (r != -1) return; switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub const PM_NOREMOVE = 0x0000; pub const PM_REMOVE = 0x0001; pub const PM_NOYIELD = 0x0002; pub extern "user32" fn PeekMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, wRemoveMsg: UINT) callconv(WINAPI) BOOL; pub fn peekMessageA(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32) !bool { const r = PeekMessageA(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg); if (r == 0) return false; if (r != -1) return true; switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn PeekMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, wRemoveMsg: UINT) callconv(WINAPI) BOOL; pub var pfnPeekMessageW: @TypeOf(PeekMessageW) = undefined; pub fn peekMessageW(lpMsg: *MSG, hWnd: ?HWND, wMsgFilterMin: u32, wMsgFilterMax: u32, wRemoveMsg: u32) !bool { const function = selectSymbol(PeekMessageW, pfnPeekMessageW, .win2k); const r = function(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg); if (r == 0) return false; if (r != -1) return true; switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn TranslateMessage(lpMsg: *const MSG) callconv(WINAPI) BOOL; pub fn translateMessage(lpMsg: *const MSG) bool { return if (TranslateMessage(lpMsg) == 0) false else true; } pub extern "user32" fn DispatchMessageA(lpMsg: *const MSG) callconv(WINAPI) LRESULT; pub fn dispatchMessageA(lpMsg: *const MSG) LRESULT { return DispatchMessageA(lpMsg); } pub extern "user32" fn DispatchMessageW(lpMsg: *const MSG) callconv(WINAPI) LRESULT; pub var pfnDispatchMessageW: @TypeOf(DispatchMessageW) = undefined; pub fn dispatchMessageW(lpMsg: *const MSG) LRESULT { const function = selectSymbol(DispatchMessageW, pfnDispatchMessageW, .win2k); return function(lpMsg); } pub extern "user32" fn PostQuitMessage(nExitCode: i32) callconv(WINAPI) void; pub fn postQuitMessage(nExitCode: i32) void { PostQuitMessage(nExitCode); } pub extern "user32" fn DefWindowProcA(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT; pub fn defWindowProcA(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) LRESULT { return DefWindowProcA(hWnd, Msg, wParam, lParam); } pub extern "user32" fn DefWindowProcW(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) callconv(WINAPI) LRESULT; pub var pfnDefWindowProcW: @TypeOf(DefWindowProcW) = undefined; pub fn defWindowProcW(hWnd: HWND, Msg: UINT, wParam: WPARAM, lParam: LPARAM) LRESULT { const function = selectSymbol(DefWindowProcW, pfnDefWindowProcW, .win2k); return function(hWnd, Msg, wParam, lParam); } // === Windows === pub const CS_VREDRAW = 0x0001; pub const CS_HREDRAW = 0x0002; pub const CS_DBLCLKS = 0x0008; pub const CS_OWNDC = 0x0020; pub const CS_CLASSDC = 0x0040; pub const CS_PARENTDC = 0x0080; pub const CS_NOCLOSE = 0x0200; pub const CS_SAVEBITS = 0x0800; pub const CS_BYTEALIGNCLIENT = 0x1000; pub const CS_BYTEALIGNWINDOW = 0x2000; pub const CS_GLOBALCLASS = 0x4000; pub const WNDCLASSEXA = extern struct { cbSize: UINT = @sizeOf(WNDCLASSEXA), style: UINT, lpfnWndProc: WNDPROC, cbClsExtra: i32 = 0, cbWndExtra: i32 = 0, hInstance: HINSTANCE, hIcon: ?HICON, hCursor: ?HCURSOR, hbrBackground: ?HBRUSH, lpszMenuName: ?[*:0]const u8, lpszClassName: [*:0]const u8, hIconSm: ?HICON, }; pub const WNDCLASSEXW = extern struct { cbSize: UINT = @sizeOf(WNDCLASSEXW), style: UINT, lpfnWndProc: WNDPROC, cbClsExtra: i32 = 0, cbWndExtra: i32 = 0, hInstance: HINSTANCE, hIcon: ?HICON, hCursor: ?HCURSOR, hbrBackground: ?HBRUSH, lpszMenuName: ?[*:0]const u16, lpszClassName: [*:0]const u16, hIconSm: ?HICON, }; pub extern "user32" fn RegisterClassExA(*const WNDCLASSEXA) callconv(WINAPI) ATOM; pub fn registerClassExA(window_class: *const WNDCLASSEXA) !ATOM { const atom = RegisterClassExA(window_class); if (atom != 0) return atom; switch (GetLastError()) { .CLASS_ALREADY_EXISTS => return error.AlreadyExists, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn RegisterClassExW(*const WNDCLASSEXW) callconv(WINAPI) ATOM; pub var pfnRegisterClassExW: @TypeOf(RegisterClassExW) = undefined; pub fn registerClassExW(window_class: *const WNDCLASSEXW) !ATOM { const function = selectSymbol(RegisterClassExW, pfnRegisterClassExW, .win2k); const atom = function(window_class); if (atom != 0) return atom; switch (GetLastError()) { .CLASS_ALREADY_EXISTS => return error.AlreadyExists, .CALL_NOT_IMPLEMENTED => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn UnregisterClassA(lpClassName: [*:0]const u8, hInstance: HINSTANCE) callconv(WINAPI) BOOL; pub fn unregisterClassA(lpClassName: [*:0]const u8, hInstance: HINSTANCE) !void { if (UnregisterClassA(lpClassName, hInstance) == 0) { switch (GetLastError()) { .CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist, else => |err| return windows.unexpectedError(err), } } } pub extern "user32" fn UnregisterClassW(lpClassName: [*:0]const u16, hInstance: HINSTANCE) callconv(WINAPI) BOOL; pub var pfnUnregisterClassW: @TypeOf(UnregisterClassW) = undefined; pub fn unregisterClassW(lpClassName: [*:0]const u16, hInstance: HINSTANCE) !void { const function = selectSymbol(UnregisterClassW, pfnUnregisterClassW, .win2k); if (function(lpClassName, hInstance) == 0) { switch (GetLastError()) { .CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist, else => |err| return windows.unexpectedError(err), } } } pub const WS_OVERLAPPED = 0x00000000; pub const WS_POPUP = 0x80000000; pub const WS_CHILD = 0x40000000; pub const WS_MINIMIZE = 0x20000000; pub const WS_VISIBLE = 0x10000000; pub const WS_DISABLED = 0x08000000; pub const WS_CLIPSIBLINGS = 0x04000000; pub const WS_CLIPCHILDREN = 0x02000000; pub const WS_MAXIMIZE = 0x01000000; pub const WS_CAPTION = WS_BORDER | WS_DLGFRAME; pub const WS_BORDER = 0x00800000; pub const WS_DLGFRAME = 0x00400000; pub const WS_VSCROLL = 0x00200000; pub const WS_HSCROLL = 0x00100000; pub const WS_SYSMENU = 0x00080000; pub const WS_THICKFRAME = 0x00040000; pub const WS_GROUP = 0x00020000; pub const WS_TABSTOP = 0x00010000; pub const WS_MINIMIZEBOX = 0x00020000; pub const WS_MAXIMIZEBOX = 0x00010000; pub const WS_TILED = WS_OVERLAPPED; pub const WS_ICONIC = WS_MINIMIZE; pub const WS_SIZEBOX = WS_THICKFRAME; pub const WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW; pub const WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX; pub const WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU; pub const WS_CHILDWINDOW = WS_CHILD; pub const WS_EX_DLGMODALFRAME = 0x00000001; pub const WS_EX_NOPARENTNOTIFY = 0x00000004; pub const WS_EX_TOPMOST = 0x00000008; pub const WS_EX_ACCEPTFILES = 0x00000010; pub const WS_EX_TRANSPARENT = 0x00000020; pub const WS_EX_MDICHILD = 0x00000040; pub const WS_EX_TOOLWINDOW = 0x00000080; pub const WS_EX_WINDOWEDGE = 0x00000100; pub const WS_EX_CLIENTEDGE = 0x00000200; pub const WS_EX_CONTEXTHELP = 0x00000400; pub const WS_EX_RIGHT = 0x00001000; pub const WS_EX_LEFT = 0x00000000; pub const WS_EX_RTLREADING = 0x00002000; pub const WS_EX_LTRREADING = 0x00000000; pub const WS_EX_LEFTSCROLLBAR = 0x00004000; pub const WS_EX_RIGHTSCROLLBAR = 0x00000000; pub const WS_EX_CONTROLPARENT = 0x00010000; pub const WS_EX_STATICEDGE = 0x00020000; pub const WS_EX_APPWINDOW = 0x00040000; pub const WS_EX_LAYERED = 0x00080000; pub const WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE; pub const WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST; pub const CW_USEDEFAULT = @bitCast(i32, @as(u32, 0x80000000)); pub extern "user32" fn CreateWindowExA(dwExStyle: DWORD, lpClassName: [*:0]const u8, lpWindowName: [*:0]const u8, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID) callconv(WINAPI) ?HWND; pub fn createWindowExA(dwExStyle: u32, lpClassName: [*:0]const u8, lpWindowName: [*:0]const u8, dwStyle: u32, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?*c_void) !HWND { const window = CreateWindowExA(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWindParent, hMenu, hInstance, lpParam); if (window) |win| return win; switch (GetLastError()) { .CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn CreateWindowExW(dwExStyle: DWORD, lpClassName: [*:0]const u16, lpWindowName: [*:0]const u16, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID) callconv(WINAPI) ?HWND; pub var pfnCreateWindowExW: @TypeOf(CreateWindowExW) = undefined; pub fn createWindowExW(dwExStyle: u32, lpClassName: [*:0]const u16, lpWindowName: [*:0]const u16, dwStyle: u32, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?*c_void) !HWND { const function = selectSymbol(CreateWindowExW, pfnCreateWindowExW, .win2k); const window = function(dwExStyle, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWindParent, hMenu, hInstance, lpParam); if (window) |win| return win; switch (GetLastError()) { .CLASS_DOES_NOT_EXIST => return error.ClassDoesNotExist, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn DestroyWindow(hWnd: HWND) callconv(WINAPI) BOOL; pub fn destroyWindow(hWnd: HWND) !void { if (DestroyWindow(hWnd) == 0) { switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } } pub const SW_HIDE = 0; pub const SW_SHOWNORMAL = 1; pub const SW_NORMAL = 1; pub const SW_SHOWMINIMIZED = 2; pub const SW_SHOWMAXIMIZED = 3; pub const SW_MAXIMIZE = 3; pub const SW_SHOWNOACTIVATE = 4; pub const SW_SHOW = 5; pub const SW_MINIMIZE = 6; pub const SW_SHOWMINNOACTIVE = 7; pub const SW_SHOWNA = 8; pub const SW_RESTORE = 9; pub const SW_SHOWDEFAULT = 10; pub const SW_FORCEMINIMIZE = 11; pub const SW_MAX = 11; pub extern "user32" fn ShowWindow(hWnd: HWND, nCmdShow: i32) callconv(WINAPI) BOOL; pub fn showWindow(hWnd: HWND, nCmdShow: i32) bool { return (ShowWindow(hWnd, nCmdShow) == TRUE); } pub extern "user32" fn UpdateWindow(hWnd: HWND) callconv(WINAPI) BOOL; pub fn updateWindow(hWnd: HWND) !void { if (ShowWindow(hWnd, nCmdShow) == 0) { switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } } pub extern "user32" fn AdjustWindowRectEx(lpRect: *RECT, dwStyle: DWORD, bMenu: BOOL, dwExStyle: DWORD) callconv(WINAPI) BOOL; pub fn adjustWindowRectEx(lpRect: *RECT, dwStyle: u32, bMenu: bool, dwExStyle: u32) !void { assert(dwStyle & WS_OVERLAPPED == 0); if (AdjustWindowRectEx(lpRect, dwStyle, bMenu, dwExStyle) == 0) { switch (GetLastError()) { .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } } pub const GWL_WNDPROC = -4; pub const GWL_HINSTANCE = -6; pub const GWL_HWNDPARENT = -8; pub const GWL_STYLE = -16; pub const GWL_EXSTYLE = -20; pub const GWL_USERDATA = -21; pub const GWL_ID = -12; pub extern "user32" fn GetWindowLongA(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG; pub fn getWindowLongA(hWnd: HWND, nIndex: i32) !i32 { const value = GetWindowLongA(hWnd, nIndex); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn GetWindowLongW(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG; pub var pfnGetWindowLongW: @TypeOf(GetWindowLongW) = undefined; pub fn getWindowLongW(hWnd: HWND, nIndex: i32) !i32 { const function = selectSymbol(GetWindowLongW, pfnGetWindowLongW, .win2k); const value = function(hWnd, nIndex); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn GetWindowLongPtrA(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG_PTR; pub fn getWindowLongPtrA(hWnd: HWND, nIndex: i32) !isize { // "When compiling for 32-bit Windows, GetWindowLongPtr is defined as a call to the GetWindowLong function." // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowlongptrw if (@sizeOf(LONG_PTR) == 4) return getWindowLongA(hWnd, nIndex); const value = GetWindowLongPtrA(hWnd, nIndex); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn GetWindowLongPtrW(hWnd: HWND, nIndex: i32) callconv(WINAPI) LONG_PTR; pub var pfnGetWindowLongPtrW: @TypeOf(GetWindowLongPtrW) = undefined; pub fn getWindowLongPtrW(hWnd: HWND, nIndex: i32) !isize { if (@sizeOf(LONG_PTR) == 4) return getWindowLongW(hWnd, nIndex); const function = selectSymbol(GetWindowLongPtrW, pfnGetWindowLongPtrW, .win2k); const value = function(hWnd, nIndex); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn SetWindowLongA(hWnd: HWND, nIndex: i32, dwNewLong: LONG) callconv(WINAPI) LONG; pub fn setWindowLongA(hWnd: HWND, nIndex: i32, dwNewLong: i32) !i32 { // [...] you should clear the last error information by calling SetLastError with 0 before calling SetWindowLong. // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlonga SetLastError(.SUCCESS); const value = SetWindowLongA(hWnd, nIndex, dwNewLong); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn SetWindowLongW(hWnd: HWND, nIndex: i32, dwNewLong: LONG) callconv(WINAPI) LONG; pub var pfnSetWindowLongW: @TypeOf(SetWindowLongW) = undefined; pub fn setWindowLongW(hWnd: HWND, nIndex: i32, dwNewLong: i32) !i32 { const function = selectSymbol(SetWindowLongW, pfnSetWindowLongW, .win2k); SetLastError(.SUCCESS); const value = function(hWnd, nIndex, dwNewLong); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn SetWindowLongPtrA(hWnd: HWND, nIndex: i32, dwNewLong: LONG_PTR) callconv(WINAPI) LONG_PTR; pub fn setWindowLongPtrA(hWnd: HWND, nIndex: i32, dwNewLong: isize) !isize { // "When compiling for 32-bit Windows, GetWindowLongPtr is defined as a call to the GetWindowLong function." // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowlongptrw if (@sizeOf(LONG_PTR) == 4) return setWindowLongA(hWnd, nIndex, dwNewLong); SetLastError(.SUCCESS); const value = SetWindowLongPtrA(hWnd, nIndex, dwNewLong); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn SetWindowLongPtrW(hWnd: HWND, nIndex: i32, dwNewLong: LONG_PTR) callconv(WINAPI) LONG_PTR; pub var pfnSetWindowLongPtrW: @TypeOf(SetWindowLongPtrW) = undefined; pub fn setWindowLongPtrW(hWnd: HWND, nIndex: i32, dwNewLong: isize) !isize { if (@sizeOf(LONG_PTR) == 4) return setWindowLongW(hWnd, nIndex, dwNewLong); const function = selectSymbol(SetWindowLongPtrW, pfnSetWindowLongPtrW, .win2k); SetLastError(.SUCCESS); const value = function(hWnd, nIndex, dwNewLong); if (value != 0) return value; switch (GetLastError()) { .SUCCESS => return 0, .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn GetDC(hWnd: ?HWND) callconv(WINAPI) ?HDC; pub fn getDC(hWnd: ?HWND) !HDC { const hdc = GetDC(hWnd); if (hdc) |h| return h; switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn ReleaseDC(hWnd: ?HWND, hDC: HDC) callconv(WINAPI) i32; pub fn releaseDC(hWnd: ?HWND, hDC: HDC) bool { return if (ReleaseDC(hWnd, hDC) == 1) true else false; } // === Modal dialogue boxes === pub const MB_OK = 0x00000000; pub const MB_OKCANCEL = 0x00000001; pub const MB_ABORTRETRYIGNORE = 0x00000002; pub const MB_YESNOCANCEL = 0x00000003; pub const MB_YESNO = 0x00000004; pub const MB_RETRYCANCEL = 0x00000005; pub const MB_CANCELTRYCONTINUE = 0x00000006; pub const MB_ICONHAND = 0x00000010; pub const MB_ICONQUESTION = 0x00000020; pub const MB_ICONEXCLAMATION = 0x00000030; pub const MB_ICONASTERISK = 0x00000040; pub const MB_USERICON = 0x00000080; pub const MB_ICONWARNING = MB_ICONEXCLAMATION; pub const MB_ICONERROR = MB_ICONHAND; pub const MB_ICONINFORMATION = MB_ICONASTERISK; pub const MB_ICONSTOP = MB_ICONHAND; pub const MB_DEFBUTTON1 = 0x00000000; pub const MB_DEFBUTTON2 = 0x00000100; pub const MB_DEFBUTTON3 = 0x00000200; pub const MB_DEFBUTTON4 = 0x00000300; pub const MB_APPLMODAL = 0x00000000; pub const MB_SYSTEMMODAL = 0x00001000; pub const MB_TASKMODAL = 0x00002000; pub const MB_HELP = 0x00004000; pub const MB_NOFOCUS = 0x00008000; pub const MB_SETFOREGROUND = 0x00010000; pub const MB_DEFAULT_DESKTOP_ONLY = 0x00020000; pub const MB_TOPMOST = 0x00040000; pub const MB_RIGHT = 0x00080000; pub const MB_RTLREADING = 0x00100000; pub const MB_TYPEMASK = 0x0000000F; pub const MB_ICONMASK = 0x000000F0; pub const MB_DEFMASK = 0x00000F00; pub const MB_MODEMASK = 0x00003000; pub const MB_MISCMASK = 0x0000C000; pub const IDOK = 1; pub const IDCANCEL = 2; pub const IDABORT = 3; pub const IDRETRY = 4; pub const IDIGNORE = 5; pub const IDYES = 6; pub const IDNO = 7; pub const IDCLOSE = 8; pub const IDHELP = 9; pub const IDTRYAGAIN = 10; pub const IDCONTINUE = 11; pub extern "user32" fn MessageBoxA(hWnd: ?HWND, lpText: [*:0]const u8, lpCaption: [*:0]const u8, uType: UINT) callconv(WINAPI) i32; pub fn messageBoxA(hWnd: ?HWND, lpText: [*:0]const u8, lpCaption: [*:0]const u8, uType: u32) !i32 { const value = MessageBoxA(hWnd, lpText, lpCaption, uType); if (value != 0) return value; switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } } pub extern "user32" fn MessageBoxW(hWnd: ?HWND, lpText: [*:0]const u16, lpCaption: ?[*:0]const u16, uType: UINT) callconv(WINAPI) i32; pub var pfnMessageBoxW: @TypeOf(MessageBoxW) = undefined; pub fn messageBoxW(hWnd: ?HWND, lpText: [*:0]const u16, lpCaption: [*:0]const u16, uType: u32) !i32 { const function = selectSymbol(pfnMessageBoxW, MessageBoxW, .win2k); const value = function(hWnd, lpText, lpCaption, uType); if (value != 0) return value; switch (GetLastError()) { .INVALID_WINDOW_HANDLE => unreachable, .INVALID_PARAMETER => unreachable, else => |err| return windows.unexpectedError(err), } }
lib/std/os/windows/user32.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const c = @import("c.zig"); const Environment = @import("environment.zig").Environment; const odbc = @import("types.zig"); const SqlReturn = odbc.SqlReturn; const HandleType = odbc.HandleType; const odbc_error = @import("error.zig"); const ReturnError = odbc_error.ReturnError; pub const Connection = struct { pub const Attribute = odbc.ConnectionAttribute; pub const AttributeValue = odbc.ConnectionAttributeValue; pub const InformationType = odbc.InformationType; pub const InformationTypeValue = odbc.InformationTypeValue; handle: *anyopaque, connected: bool = false, pub fn init(environment: *Environment) ReturnError!Connection { var result: Connection = undefined; const alloc_result = c.SQLAllocHandle(@enumToInt(HandleType.Connection), environment.handle, @ptrCast([*c]?*anyopaque, &result.handle)); return switch (@intToEnum(SqlReturn, alloc_result)) { .InvalidHandle => error.InvalidHandle, .Error => error.Error, else => result, }; } /// Deinitialize the connection by disconnecting from the data source (if connected) and freeing the /// connection handle. pub fn deinit(self: *Connection) !void { if (self.connected) try self.disconnect(); const result = c.SQLFreeHandle(@enumToInt(HandleType.Connection), self.handle); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => {}, else => self.getLastError(), }; } /// Try to connect to a data source using a username and password. pub fn connect(self: *Connection, server_name: []const u8, user_name: []const u8, password: []const u8) !void { const result = c.SQLConnect(self.handle, @intToPtr([*c]u8, @ptrToInt(server_name.ptr)), @intCast(i16, server_name.len), @intToPtr([*c]u8, @ptrToInt(user_name.ptr)), @intCast(i16, user_name.len), @intToPtr([*c]u8, @ptrToInt(password.ptr)), @intCast(i16, password.len)); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => { self.connected = true; }, // @todo Async handling else => self.getLastError(), }; } /// Try to connect to a data source using a connection string. Use the `completion` parameter to determine how the driver /// should handle missing parameters in the connection string. For most non-interactive programs, the appropriate completion /// type is `.NoPrompt`. pub fn connectExtended(self: *Connection, connection_string: []const u8, completion: odbc.DriverCompletion) !void { const result = c.SQLDriverConnect(self.handle, null, @intToPtr([*c]u8, @ptrToInt(connection_string.ptr)), @intCast(c_short, connection_string.len), null, 0, null, @enumToInt(completion)); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => { self.connected = true; }, // @todo Async handling else => self.getLastError(), }; } /// `browseConnect` is intended to be called multiple times. Each time, the user can pass a connection string with some, all, or none of /// the parameters required to establish a connection. `browseConnect` will return a string that resembles a connection string, which /// contains the information missing from the previous call. /// /// If the user passes all of the necessary parameters, then a connection is established and `browseConnect` will return `null`. pub fn browseConnect(self: *Connection, allocator: Allocator, partial_connection_string: []const u8) !?[]const u8 { var out_string_len: c.SQLSMALLINT = 0; var out_string_buffer = try allocator.alloc(u8, 100); errdefer allocator.free(out_string_buffer); run_loop: while (true) { const result = c.SQLBrowseConnect(self.handle, partial_connection_string.ptr, partial_connection_string.len, out_string_buffer.ptr, out_string_buffer.len, &out_string_len); switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => { // If SQLBrowseConnect returns success, then the user passed all required info and the connection should be established. // Set connected to true and return null to indicate that there is no more info needed. self.connected = true; allocator.free(out_string_buffer); return null; }, .NeedsData => { if (std.mem.eql(u8, partial_connection_string, out_string_buffer)) { // If SQLBrowseConnect returns NeedsData and the out string is unchanged from the input string, that means that there are // unrecoverable errors. return self.getLastError(); } // Otherwise, when NeedsData is returned out_string_buffer contains a connection string-like value that indicates // to the user what info they need to pass next return out_string_buffer; }, .InvalidHandle => @panic("Connection.browseConnect passed invalid handle"), else => switch (self.getLastError()) { error.StringRightTrunc => { out_string_buffer = try allocator.realloc(out_string_buffer, @intCast(usize, out_string_len) + 1); continue :run_loop; }, else => |err| return err, }, } } } /// Disconnect from the data source. If not connected to a data source, does nothing. /// `deinit` still needs to be called after this function to fully deinitialize a `Connection`. pub fn disconnect(self: *Connection) !void { if (!self.connected) return; const result = c.SQLDisconnect(self.handle); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => { self.connected = false; }, // @todo Async handling else => self.getLastError(), }; } /// Commit or rollback all open transactions on any statement associated with this connection. pub fn endTransaction(self: *Connection, completion_type: odbc.CompletionType) !void { const result = c.SQLEndTran(@enumToInt(HandleType.Connection), self.handle, @enumToInt(completion_type)); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => {}, .InvalidHandle => @panic("Connection.endTransaction passed invalid handle"), else => self.getLastError(), }; } /// Cancel an in-progress function. This could be a function that returned `StillProcessing`, `NeedsData`, or /// a function that is actively processing on another thread. pub fn cancel(self: *Connection) !void { const result = c.SQLCancelHandle(@enumToInt(HandleType.Connection), self.handle); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => {}, .InvalidHandle => @panic("Connection.cancel passed invalid handle"), else => self.getLastError(), }; } /// Return `true` if this driver supports the specified function, `false` otherwise. If any error occurs /// while running this function, returns `false`. pub fn isFunctionEnabled(self: *Connection, function_id: odbc.FunctionId) bool { var supported: c.SQLUSMALLINT = 0; const result = c.SQLGetFunctions(self.handle, @enumToInt(function_id), &supported); return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => supported == c.SQL_TRUE, else => false, }; } /// Get all of the functions supported by this driver. pub fn getAllEnabledFunctions(self: *Connection, allocator: Allocator) ![]odbc.FunctionId { var result_buffer: [c.SQL_API_ODBC3_ALL_FUNCTIONS_SIZE]c.SQLUSMALLINT = undefined; var result_list = std.ArrayList(odbc.FunctionId).init(allocator); const result = c.SQLGetFunctions(self.handle, c.SQL_API_ODBC3_ALL_FUNCTIONS, @ptrCast([*c]c_ushort, &result_buffer)); switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => { // Iterate over all of the function ids and check if they exist. inline for (@typeInfo(odbc.FunctionId).Enum.fields) |field| { // Recreates the following macro: // SQL_FUNC_EXISTS(pfExists,uwAPI) ((*(((UWORD*) (pfExists)) + ((uwAPI) >> 4)) & (1 << ((uwAPI) & 0x000F))) ? SQL_TRUE : SQL_FALSE) const func_exists = (@ptrToInt(@ptrCast(*c_ushort, &result_buffer)) + (field.value >> 4)) & (1 << (field.value & 0x000F)) != 0; if (func_exists) { try result_list.append(@intToEnum(odbc.FunctionId, field.value)); } } return result_list.toOwnedSlice(); }, else => return self.getLastError(), } } /// Given a SQL statement, return the same statement as modified by the current driver. pub fn nativeSql(self: *Connection, allocator: Allocator, sql_statement: []const u8) ![]const u8 { var out_statement_len: c.SQLINTEGER = 0; // Allocate a buffer for the out string, allocate the same number of chars as the in string because it's likely to be // close var out_statement_buffer = allocator.alloc(u8, sql_statement.len); errdefer allocator.free(out_statement_buffer); run_loop: while (true) { const result = c.SQLNativeSql(self.handle, sql_statement.ptr, sql_statement.len, out_statement_buffer.ptr, out_statement_buffer.len, &out_statement_len); switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => return out_statement_buffer, .InvalidHandle => @panic("Connection.nativeSql passed invalid handle"), else => switch (self.getLastError()) { error.StringRightTrunc => { // If the out string was truncated, realloc to the correct length and run again out_statement_buffer = try allocator.realloc(out_statement_buffer, @intCast(usize, out_statement_len) + 1); continue :run_loop; }, else => |err| return err, }, } } } pub fn getInfo(self: *Connection, comptime info_type: InformationType, allocator: Allocator) !InformationTypeValue { var result_buffer = try allocator.alloc(u8, 200); errdefer allocator.free(result_buffer); var result_string_length: c.SQLSMALLINT = 0; run_loop: while (true) { const result = c.SQLGetInfo(self.handle, @enumToInt(info_type), result_buffer.ptr, @intCast(c.SQLSMALLINT, result_buffer.len), &result_string_length); switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => { const value = info_type.getValue(result_buffer, @intCast(usize, result_string_length)); if (!value.isStringType()) { allocator.free(result_buffer); } return value; }, .InvalidHandle => @panic("Connection.getInfo passed invalid handle"), else => switch (self.getLastError()) { error.StringRightTrunc => { result_buffer = try allocator.realloc(result_buffer, @intCast(usize, result_string_length)); continue :run_loop; }, else => |err| return err, }, } } } pub fn getAttribute(self: *Connection, comptime attribute: Attribute, allocator: Allocator) !?AttributeValue { var value = try allocator.alloc(u8, 100); defer allocator.free(value); var attribute_str_len: i32 = 0; attr_loop: while (true) { const result = c.SQLGetConnectAttr(self.handle, @enumToInt(attribute), value.ptr, @intCast(c_long, value.len), &attribute_str_len); switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => return attribute.getAttributeValue(value), .NoData => return null, .InvalidHandle => @panic("Connection.getAttribute passed invalid handle"), else => switch (self.getLastError()) { error.StringRightTrunc => { value = try allocator.realloc(value, @intCast(usize, attribute_str_len) + 1); continue :attr_loop; }, else => |err| return err, }, } } } pub fn setAttribute(self: *Connection, value: AttributeValue) !void { const result = switch (value) { // For string attributes, pass the pointers to the strings directly .CurrentCatalog => |v| c.SQLSetConnectAttr(self.handle, @enumToInt(value), v.ptr, @intCast(c_int, v.len)), .Tracefile, .TranslateLib => |v| c.SQLSetConnectAttr(self.handle, @enumToInt(value), v.ptr, @intCast(c_int, v.len)), else => blk: { // For integer attributes, get the value and then cast it to ?*anyopaque to pass it on var result_buffer: [@sizeOf(u32)]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(result_buffer[0..]); _ = try value.getValue(fba.allocator()); const int_val = std.mem.bytesToValue(u32, &result_buffer); break :blk c.SQLSetConnectAttr(self.handle, @enumToInt(std.meta.activeTag(value)), @intToPtr(?*anyopaque, int_val), 0); }, }; return switch (@intToEnum(SqlReturn, result)) { .Success, .SuccessWithInfo => {}, .InvalidHandle => @panic("Connection.setAttribute passed invalid handle"), else => self.getLastError(), }; } pub fn getLastError(self: *const Connection) odbc_error.LastError { return odbc_error.getLastError(odbc.HandleType.Connection, self.handle); } pub fn getErrors(self: *Connection, allocator: Allocator) ![]odbc_error.SqlState { return try odbc_error.getErrors(allocator, odbc.HandleType.Connection, self.handle); } pub fn getDiagnosticRecords(self: *Connection, allocator: Allocator) ![]odbc_error.DiagnosticRecord { return try odbc_error.getDiagnosticRecords(allocator, odbc.HandleType.Connection, self.handle); } };
src/connection.zig
const inputFile = @embedFile("./input/day05.txt"); const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const assert = std.debug.assert; fn parseU16(buf: []const u8) std.fmt.ParseIntError!u16 { return std.fmt.parseInt(u16, buf, 10); } const Point = struct { // consts const pointShift: u8 = 16; // data x: u16, y: u16, }; const PointContext = struct { // These functions meet the Hash table implementation (it's a bit wonky, but thats how the stdlib does it too) pub fn hash(self: @This(), pt: Point) u64 { _ = self; return (@as(u64, pt.x) << Point.pointShift) + pt.y; } pub fn eql(self: @This(), p1: Point, p2: Point) bool { const v1: u64 = hash(self, p1); const v2: u64 = hash(self, p2); return v1 == v2; } }; const LineSegment = struct { startX: u16, startY: u16, endX: u16, endY: u16, pub fn isStraightLine(self: @This()) bool { return self.isHorizontal() or self.isVertical(); } pub fn isHorizontal(self: @This()) bool { return self.startY == self.endY; } pub fn isVertical(self: @This()) bool { return self.startX == self.endX; } // printf implementation pub fn format(self: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("({d} {d}) -> ({d} {d})", .{ self.startX, self.startY, self.endX, self.endY }); } }; fn parseInput(input: []const u8, allocator: Allocator) !ArrayList(LineSegment) { var lines = ArrayList(LineSegment).init(allocator); errdefer lines.deinit(); var start: usize = 0; while (std.mem.indexOfScalarPos(u8, input, start, '\n') != null) { var startX = blk: { const end = std.mem.indexOfScalarPos(u8, input, start, ',').?; const num = try parseU16(input[start..end]); start = end + 1; break :blk num; }; var startY = blk: { const end = std.mem.indexOfScalarPos(u8, input, start, ' ').?; const num = try parseU16(input[start..end]); start = end + 1; break :blk num; }; // skip arrow const arrowLen = "-> ".len; start += arrowLen; var endX = blk: { const end = std.mem.indexOfScalarPos(u8, input, start, ',').?; const num = try parseU16(input[start..end]); start = end + 1; break :blk num; }; var endY = blk: { const end = std.mem.indexOfScalarPos(u8, input, start, '\n').?; const num = try parseU16(input[start..end]); start = end + 1; break :blk num; }; // Sort the endpoints to make our lives easier if (startX == endX and startY > endY) { std.mem.swap(u16, &startY, &endY); } else if (startX > endX) { std.mem.swap(u16, &startX, &endX); std.mem.swap(u16, &startY, &endY); } try lines.append(.{ .startX = startX, .startY = startY, .endX = endX, .endY = endY, }); } return lines; } fn between(x: u16, y: u16, z: u16) bool { if (x < z) { return x <= y and y <= z; } else { return z <= y and y <= x; } } /// End result is that either a1 < b1 or a1 -- a2 encompasses b1 -- b2 fn swapPoints(a1: *u16, a2: *u16, b1: *u16, b2: *u16) void { // Leave this comment in: it shows we handle all 3 cases // if (*a1 < *b1) return if (a1.* > b1.*) { std.mem.swap(u16, a1, b1); std.mem.swap(u16, a2, b2); } if (a1.* == b1.* and a2.* < b2.*) { std.mem.swap(u16, a2, b2); } } const LineType = enum { Horizontal, Vertical, }; const PointsSet = std.HashMap(Point, void, PointContext, std.hash_map.default_max_load_percentage); fn countOverlaps(pointsSeen: *PointsSet, a1: u16, a2: u16, b1: u16, b2: u16, l1: LineSegment, _: LineSegment, lineType: LineType) !void { // const typeName = switch (lineType) { // .Vertical => "Vertical", // .Horizontal => "Horizontal", // }; assert(a1 <= b1); // Case 0: (no overlap) a2 < b1 // a1 --------- a2 b1 ---------- b2 if (a2 < b1) { return; } // Case 1: (partial overlap) b1 <= a2 and a2 < b2 // a1 --------- b1 ===== a2 ---------- b2 if (b1 <= a2 and a2 < b2) { // std.debug.print("{s} Case 1: {d} -- {d} -- {d} -- {d} == {any}, {any}\n", .{ typeName, a1, b1, a2, b2, l1, l2 }); var b1_ = b1; while (b1_ <= a2) : (b1_ += 1) { const point = switch (lineType) { .Vertical => Point{ .x = l1.startX, .y = b1_ }, .Horizontal => Point{ .x = b1_, .y = l1.startY }, }; // std.debug.print("putting point: {any}\n", .{point}); try pointsSeen.put(point, undefined); } return; } // Case 2: (full overlap) b1 < a2 and b2 <= a2 // a1 --------- b1 ===== b2 ---------- a2 if (b1 < a2 and b2 <= a2) { // std.debug.print("{s} Case 2: {d} -- {d} -- {d} -- {d}== {any}, {any}\n", .{ typeName, a1, b1, b2, a2, l1, l2 }); var b1_ = b1; while (b1_ <= b2) : (b1_ += 1) { const point = switch (lineType) { .Vertical => Point{ .x = l1.startX, .y = b1_ }, .Horizontal => Point{ .x = b1_, .y = l1.startY }, }; // std.debug.print("putting point: {any}\n", .{point}); try pointsSeen.put(point, undefined); } return; } unreachable; } // Part 1 // Straight lines simplifies this a lot, we now have that only horizontal lines can intersect with vertical lines // and with themselves fn numIntersectionsStraight(horizontalLines: []LineSegment, verticalLines: []LineSegment, allocator: Allocator) !u32 { var pointsSeen = PointsSet.init(allocator); defer pointsSeen.deinit(); // 1) Vertical with vertical for (verticalLines) |l1, i| { var j: usize = i + 1; while (j < verticalLines.len) : (j += 1) { var l2 = verticalLines[j]; if (l1.startX != l2.startX) { continue; } var a1: u16 = l1.startY; var a2: u16 = l1.endY; var b1: u16 = l2.startY; var b2: u16 = l2.endY; swapPoints(&a1, &a2, &b1, &b2); try countOverlaps(&pointsSeen, a1, a2, b1, b2, l1, l2, .Vertical); } } for (horizontalLines) |horizontalLine, i| { // ------------- 2) horizontal with horizontal const l1 = horizontalLine; // consistent with naming above var j: usize = i + 1; while (j < horizontalLines.len) : (j += 1) { var l2 = horizontalLines[j]; if (l1.startY != l2.startY) { continue; } var a1: u16 = l1.startX; var a2: u16 = l1.endX; var b1: u16 = l2.startX; var b2: u16 = l2.endX; swapPoints(&a1, &a2, &b1, &b2); try countOverlaps(&pointsSeen, a1, a2, b1, b2, l1, l2, .Horizontal); } //------------- 3) horizontal with vertical for (verticalLines) |verticalLine| { if (between(horizontalLine.startX, verticalLine.startX, horizontalLine.endX) and between(verticalLine.startY, horizontalLine.startY, verticalLine.endY)) { // std.debug.print("Case 3: {any}, {any}\n", .{ horizontalLine, verticalLine }); const p = Point{ .x = verticalLine.startX, .y = horizontalLine.startY, }; // std.debug.print("putting point: {any}\n", .{p}); try pointsSeen.put(p, undefined); } } } return pointsSeen.count(); } // --------------- Part 2 ----------------------- // So for this part I just gave up and decided to try a different approach, // this time I'm just filling out a grid of numbers and counting intersections // Reaons being that I noticed that the max values are not very high (<1000) so this is feasible // So the approach is 100% different from part 1. // The part1 code is more generic since points can be unbounded (I used u16 so it only works for numbers up to 65535 but that's plenty big.) // Here, the width * height must be a reasonable number const GridDimensions = struct { width: u32, height: u32, }; fn computeGridDimensions(lines: []LineSegment) GridDimensions { // Compute dimentions var width: u32 = 0; var height: u32 = 0; for (lines) |line| { // lines are guaranteed to be ordered in terms of (x, y) if (line.endX > width) { width = line.endX; } if (line.endY > height) { height = line.endY; } } width += 1; // 0 height += 1; // 0 return .{ .width = width, .height = height, }; } fn debugPrintGrid(grid: []u16, dimensions: GridDimensions) void { assert(grid.len == (dimensions.width * dimensions.height)); var row: usize = 0; while (row < dimensions.height) : (row += 1) { var col: u32 = 0; while (col < dimensions.width) : (col += 1) { const x = grid[row * dimensions.width + col]; if (x == 0) { std.debug.print(". ", .{}); } else { std.debug.print("{d} ", .{x}); } } std.debug.print("\n", .{}); } std.debug.print("\n", .{}); } fn partTwo(lines: []LineSegment, allocator: Allocator) !u32 { const dimensions = computeGridDimensions(lines); var grid = try allocator.alloc(u16, dimensions.width * dimensions.height); defer allocator.free(grid); std.mem.set(u16, grid, 0); for (lines) |line| { if (line.isHorizontal()) { const row = line.startY; var col = line.startX; while (col <= line.endX) : (col += 1) { grid[row * dimensions.width + col] += 1; } } else if (line.isVertical()) { const col = line.startX; var row = line.startY; while (row <= line.endY) : (row += 1) { grid[row * dimensions.width + col] += 1; } } else { // diagonal line const dist = line.endX - line.startX; assert((try std.math.absInt(@as(i32, line.endY) - @as(i32, line.startY))) == dist); if (line.startY < line.endY) { // downwards var i: u16 = 0; while (i <= dist) : (i += 1) { grid[(line.startY + i) * dimensions.width + (line.startX + i)] += 1; } } else { // upwards var i: u16 = 0; while (i <= dist) : (i += 1) { grid[(line.startY - i) * dimensions.width + (line.startX + i)] += 1; } } } } // debugPrintGrid(grid, dimensions); var result: u32 = 0; for (grid) |x| { if (x > 1) result += 1; } return result; } pub fn main() !void { const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; defer std.debug.assert(!gpa.deinit()); // no leaks var lines = try parseInput(inputFile, allocator); defer lines.deinit(); // Part 1 { var horizontalLines = ArrayList(LineSegment).init(allocator); defer horizontalLines.deinit(); var verticalLines = ArrayList(LineSegment).init(allocator); defer verticalLines.deinit(); // Part 1 for (lines.items) |line| { if (line.isHorizontal()) { try horizontalLines.append(line); } else if (line.isVertical()) { try verticalLines.append(line); } } try stdout.print("Part 1 Num points cross: {d}\n", .{try numIntersectionsStraight(horizontalLines.items, verticalLines.items, allocator)}); } // Part 2 { try stdout.print("Part 2 Num points cross: {d}\n", .{try partTwo(lines.items, allocator)}); } } test "Part 1 sample" { const input = \\0,9 -> 5,9 \\8,0 -> 0,8 \\9,4 -> 3,4 \\2,2 -> 2,1 \\7,0 -> 7,4 \\6,4 -> 2,0 \\0,9 -> 2,9 \\3,4 -> 1,4 \\0,0 -> 8,8 \\5,5 -> 8,2 \\ ; const allocator = std.testing.allocator; var lines = try parseInput(input, allocator); defer lines.deinit(); var horizontalLines = ArrayList(LineSegment).init(allocator); defer horizontalLines.deinit(); var verticalLines = ArrayList(LineSegment).init(allocator); defer verticalLines.deinit(); // Part 1 for (lines.items) |line| { if (line.isHorizontal()) { try horizontalLines.append(line); } else if (line.isVertical()) { try verticalLines.append(line); } } try std.testing.expectEqual(@as(u32, 5), try numIntersectionsStraight(horizontalLines.items, verticalLines.items, allocator)); } test "Part 1 sample extended" { const input = \\2,0 -> 2,9 \\0,9 -> 5,9 \\8,0 -> 0,8 \\9,4 -> 3,4 \\2,2 -> 2,1 \\7,0 -> 7,4 \\6,4 -> 2,0 \\0,9 -> 2,9 \\3,4 -> 1,4 \\0,0 -> 8,8 \\5,5 -> 8,2 \\ ; const allocator = std.testing.allocator; var lines = try parseInput(input, allocator); defer lines.deinit(); var horizontalLines = ArrayList(LineSegment).init(allocator); defer horizontalLines.deinit(); var verticalLines = ArrayList(LineSegment).init(allocator); defer verticalLines.deinit(); // Part 1 for (lines.items) |line| { if (line.isHorizontal()) { try horizontalLines.append(line); } else if (line.isVertical()) { try verticalLines.append(line); } } try std.testing.expectEqual(@as(u32, 8), try numIntersectionsStraight(horizontalLines.items, verticalLines.items, allocator)); } test "Part 2 sample" { const input = \\0,9 -> 5,9 \\8,0 -> 0,8 \\9,4 -> 3,4 \\2,2 -> 2,1 \\7,0 -> 7,4 \\6,4 -> 2,0 \\0,9 -> 2,9 \\3,4 -> 1,4 \\0,0 -> 8,8 \\5,5 -> 8,2 \\ ; const allocator = std.testing.allocator; var lines = try parseInput(input, allocator); defer lines.deinit(); std.debug.print("\n", .{}); try std.testing.expectEqual(@as(u32, 12), try partTwo(lines.items, allocator)); }
src/day05.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("zar", "src/main.zig"); var tests = b.addTest("src/test.zig"); var tests_exe = b.addTestExe("test", "src/test.zig"); const build_test_executable_only = b.option(bool, "build-tests", "Build tests but don't run them.") orelse false; const exe_options = b.addOptions(); exe.addOptions("build_options", exe_options); tests.addOptions("build_options", exe_options); tests_exe.addOptions("build_options", exe_options); { const tracy = b.option([]const u8, "tracy", "Enable Tracy integration. Supply path to Tracy source"); const tracy_callstack = b.option(bool, "tracy-callstack", "Include callstack information with Tracy data. Does nothing if -Dtracy is not provided") orelse false; const tracy_allocation = b.option(bool, "tracy-allocation", "Include allocation information with Tracy data. Does nothing if -Dtracy is not provided") orelse false; exe_options.addOption(bool, "enable_tracy", tracy != null); exe_options.addOption(bool, "enable_tracy_callstack", tracy_callstack); exe_options.addOption(bool, "enable_tracy_allocation", tracy_allocation); // "-DTRACY_NO_EXIT=1" if (tracy) |tracy_path| { const client_cpp = std.fs.path.join( b.allocator, &[_][]const u8{ tracy_path, "TracyClient.cpp" }, ) catch unreachable; // On mingw, we need to opt into windows 7+ to get some features required by tracy. const tracy_c_flags: []const []const u8 = if (target.isWindows() and target.getAbi() == .gnu) &[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined", "-D_WIN32_WINNT=0x601" } else &[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" }; exe.addIncludePath(tracy_path); exe.addCSourceFile(client_cpp, tracy_c_flags); exe.linkLibC(); exe.linkLibCpp(); tests.addIncludePath(tracy_path); tests.addCSourceFile(client_cpp, tracy_c_flags); tests.linkLibC(); tests.linkLibCpp(); if (target.isWindows()) { exe.linkSystemLibrary("dbghelp"); exe.linkSystemLibrary("ws2_32"); tests.linkSystemLibrary("dbghelp"); tests.linkSystemLibrary("ws2_32"); } else if (target.isDarwin()) { exe.linkFramework("CoreFoundation"); tests.linkFramework("CoreFoundation"); } } } exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); if (build_test_executable_only) { const test_step = b.step("test", "Run tests"); test_step.dependOn(&tests_exe.step); tests_exe.emit_bin = .{ .emit_to = "zig-out/bin/test" }; } else { const test_step = b.step("test", "Run tests"); test_step.dependOn(&tests.step); } }
build.zig
const testing = @import("std").testing; const mem = @import("std").mem; const c = @import("c.zig").c; /// Errors that GLFW can produce. pub const Error = error{ /// GLFW has not been initialized. /// /// This occurs if a GLFW function was called that must not be called unless the library is /// initialized. NotInitialized, /// No context is current for this thread. /// /// This occurs if a GLFW function was called that needs and operates on the current OpenGL or /// OpenGL ES context but no context is current on the calling thread. One such function is /// glfw.SwapInterval. NoCurrentContext, /// One of the arguments to the function was an invalid enum value. /// /// One of the arguments to the function was an invalid enum value, for example requesting /// glfw.red_bits with glfw.getWindowAttrib. InvalidEnum, /// One of the arguments to the function was an invalid value. /// /// One of the arguments to the function was an invalid value, for example requesting a /// non-existent OpenGL or OpenGL ES version like 2.7. /// /// Requesting a valid but unavailable OpenGL or OpenGL ES version will instead result in a /// glfw.Error.VersionUnavailable error. InvalidValue, /// A memory allocation failed. OutOfMemory, /// GLFW could not find support for the requested API on the system. /// /// The installed graphics driver does not support the requested API, or does not support it /// via the chosen context creation API. Below are a few examples. /// /// Some pre-installed Windows graphics drivers do not support OpenGL. AMD only supports /// OpenGL ES via EGL, while Nvidia and Intel only support it via a WGL or GLX extension. macOS /// does not provide OpenGL ES at all. The Mesa EGL, OpenGL and OpenGL ES libraries do not /// interface with the Nvidia binary driver. Older graphics drivers do not support Vulkan. APIUnavailable, /// The requested OpenGL or OpenGL ES version (including any requested context or framebuffer /// hints) is not available on this machine. /// /// The machine does not support your requirements. If your application is sufficiently /// flexible, downgrade your requirements and try again. Otherwise, inform the user that their /// machine does not match your requirements. /// /// Future invalid OpenGL and OpenGL ES versions, for example OpenGL 4.8 if 5.0 comes out /// before the 4.x series gets that far, also fail with this error and not glfw.Error.InvalidValue, /// because GLFW cannot know what future versions will exist. VersionUnavailable, /// A platform-specific error occurred that does not match any of the more specific categories. /// /// A bug or configuration error in GLFW, the underlying operating system or its drivers, or a /// lack of required resources. Report the issue to our [issue tracker](https://github.com/glfw/glfw/issues). PlatformError, /// The requested format is not supported or available. /// /// If emitted during window creation, the requested pixel format is not supported. /// /// If emitted when querying the clipboard, the contents of the clipboard could not be /// converted to the requested format. /// /// If emitted during window creation, one or more hard constraints did not match any of the /// available pixel formats. If your application is sufficiently flexible, downgrade your /// requirements and try again. Otherwise, inform the user that their machine does not match /// your requirements. /// /// If emitted when querying the clipboard, ignore the error or report it to the user, as /// appropriate. FormatUnavailable, /// The specified window does not have an OpenGL or OpenGL ES context. /// /// A window that does not have an OpenGL or OpenGL ES context was passed to a function that /// requires it to have one. NoWindowContext, /// The specified cursor shape is not available. /// /// The specified standard cursor shape is not available, either because the /// current platform cursor theme does not provide it or because it is not /// available on the platform. /// /// analysis: Platform or system settings limitation. Pick another standard cursor shape or /// create a custom cursor. CursorUnavailable, /// The requested feature is not provided by the platform. /// /// The requested feature is not provided by the platform, so GLFW is unable to /// implement it. The documentation for each function notes if it could emit /// this error. /// /// analysis: Platform or platform version limitation. The error can be ignored /// unless the feature is critical to the application. /// /// A function call that emits this error has no effect other than the error and /// updating any existing out parameters. /// FeatureUnavailable, /// The requested feature is not implemented for the platform. /// /// The requested feature has not yet been implemented in GLFW for this platform. /// /// analysis: An incomplete implementation of GLFW for this platform, hopefully /// fixed in a future release. The error can be ignored unless the feature is /// critical to the application. /// /// A function call that emits this error has no effect other than the error and /// updating any existing out parameters. /// FeatureUnimplemented, /// Platform unavailable or no matching platform was found. /// /// If emitted during initialization, no matching platform was found. If glfw.InitHint.platform /// is set to `.any_platform`, GLFW could not detect any of the platforms supported by this /// library binary, except for the Null platform. If set to a specific platform, it is either /// not supported by this library binary or GLFW was not able to detect it. /// /// If emitted by a native access function, GLFW was initialized for a different platform /// than the function is for. /// /// analysis: Failure to detect any platform usually only happens on non-macOS Unix /// systems, either when no window system is running or the program was run from /// a terminal that does not have the necessary environment variables. Fall back to /// a different platform if possible or notify the user that no usable platform was /// detected. /// /// Failure to detect a specific platform may have the same cause as above or be because /// support for that platform was not compiled in. Call glfw.platformSupported to /// check whether a specific platform is supported by a library binary. /// PlatformUnavailable, }; fn convertError(e: c_int) Error!void { return switch (e) { c.GLFW_NO_ERROR => {}, c.GLFW_NOT_INITIALIZED => Error.NotInitialized, c.GLFW_NO_CURRENT_CONTEXT => Error.NoCurrentContext, c.GLFW_INVALID_ENUM => Error.InvalidEnum, c.GLFW_INVALID_VALUE => Error.InvalidValue, c.GLFW_OUT_OF_MEMORY => Error.OutOfMemory, c.GLFW_API_UNAVAILABLE => Error.APIUnavailable, c.GLFW_VERSION_UNAVAILABLE => Error.VersionUnavailable, c.GLFW_PLATFORM_ERROR => Error.PlatformError, c.GLFW_FORMAT_UNAVAILABLE => Error.FormatUnavailable, c.GLFW_NO_WINDOW_CONTEXT => Error.NoWindowContext, c.GLFW_CURSOR_UNAVAILABLE => Error.CursorUnavailable, c.GLFW_FEATURE_UNAVAILABLE => Error.FeatureUnavailable, c.GLFW_FEATURE_UNIMPLEMENTED => Error.FeatureUnimplemented, c.GLFW_PLATFORM_UNAVAILABLE => Error.PlatformUnavailable, else => unreachable, }; } /// Returns and clears the last error for the calling thread. /// /// This function returns and clears the error code of the last error that occurred on the calling /// thread, and optionally a UTF-8 encoded human-readable description of it. If no error has /// occurred since the last call, it returns GLFW_NO_ERROR (zero) and the description pointer is /// set to `NULL`. /// /// * @param[in] description Where to store the error description pointer, or `NULL`. /// @return The last error code for the calling thread, or @ref GLFW_NO_ERROR (zero). /// /// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it /// yourself. It is guaranteed to be valid only until the next error occurs or the library is /// terminated. /// /// @remark This function may be called before @ref glfwInit. /// /// @thread_safety This function may be called from any thread. pub inline fn getError() Error!void { return convertError(c.glfwGetError(null)); } /// Returns and clears the last error description for the calling thread. /// /// This function returns a UTF-8 encoded human-readable description of the last error that occured /// on the calling thread. If no error has occurred since the last call, it returns null. /// /// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it /// yourself. It is guaranteed to be valid only until the next error occurs or the library is /// terminated. /// /// @remark This function may be called before @ref glfwInit. /// /// @thread_safety This function may be called from any thread. pub inline fn getErrorString() ?[]const u8 { var desc: [*c]const u8 = null; const error_code = c.glfwGetError(&desc); convertError(error_code) catch { return mem.sliceTo(desc, 0); }; return null; } /// Sets the error callback. /// /// This function sets the error callback, which is called with an error code /// and a human-readable description each time a GLFW error occurs. /// /// The error code is set before the callback is called. Calling @ref /// glfwGetError from the error callback will return the same value as the error /// code argument. /// /// The error callback is called on the thread where the error occurred. If you /// are using GLFW from multiple threads, your error callback needs to be /// written accordingly. /// /// Because the description string may have been generated specifically for that /// error, it is not guaranteed to be valid after the callback has returned. If /// you wish to use it after the callback returns, you need to make a copy. /// /// Once set, the error callback remains set even after the library has been /// terminated. /// /// @param[in] callback The new callback, or `NULL` to remove the currently set /// callback. /// /// @callback_param `error_code` An error code. Future releases may add more error codes. /// @callback_param `description` A UTF-8 encoded string describing the error. /// /// @errors None. /// /// @remark This function may be called before @ref glfwInit. /// /// @thread_safety This function must only be called from the main thread. pub fn setErrorCallback(comptime callback: ?fn (error_code: Error, description: [:0]const u8) void) void { if (callback) |user_callback| { const CWrapper = struct { pub fn errorCallbackWrapper(err_int: c_int, c_description: [*c]const u8) callconv(.C) void { if (convertError(err_int)) |_| { // This means the error was `GLFW_NO_ERROR` return; } else |err| { user_callback(err, mem.sliceTo(c_description, 0)); } } }; _ = c.glfwSetErrorCallback(CWrapper.errorCallbackWrapper); return; } _ = c.glfwSetErrorCallback(null); } test "errorCallback" { const TestStruct = struct { pub fn callback(_: Error, _: [:0]const u8) void {} }; setErrorCallback(TestStruct.callback); } test "error string" { try testing.expect(getErrorString() == null); }
glfw/src/errors.zig
const std = @import("../index.zig"); const builtin = @import("builtin"); const assert = std.debug.assert; const mem = std.mem; const math = std.math; const ziggurat = @import("ziggurat.zig"); // When you need fast unbiased random numbers pub const DefaultPrng = Xoroshiro128; // When you need cryptographically secure random numbers pub const DefaultCsprng = Isaac64; pub const Random = struct { fillFn: fn (r: *Random, buf: []u8) void, /// Read random bytes into the specified buffer until fill. pub fn bytes(r: *Random, buf: []u8) void { r.fillFn(r, buf); } /// Return a random integer/boolean type. pub fn scalar(r: *Random, comptime T: type) T { var rand_bytes: [@sizeOf(T)]u8 = undefined; r.bytes(rand_bytes[0..]); if (T == bool) { return rand_bytes[0] & 0b1 == 0; } else { // NOTE: Cannot @bitCast array to integer type. return mem.readInt(rand_bytes, T, builtin.Endian.Little); } } /// Get a random unsigned integer with even distribution between `start` /// inclusive and `end` exclusive. pub fn range(r: *Random, comptime T: type, start: T, end: T) T { assert(start <= end); if (T.is_signed) { const uint = @IntType(false, T.bit_count); if (start >= 0 and end >= 0) { return @intCast(T, r.range(uint, @intCast(uint, start), @intCast(uint, end))); } else if (start < 0 and end < 0) { // Can't overflow because the range is over signed ints return math.negateCast(r.range(uint, math.absCast(end), math.absCast(start)) + 1) catch unreachable; } else if (start < 0 and end >= 0) { const end_uint = @intCast(uint, end); const total_range = math.absCast(start) + end_uint; const value = r.range(uint, 0, total_range); const result = if (value < end_uint) x: { break :x @intCast(T, value); } else if (value == end_uint) x: { break :x start; } else x: { // Can't overflow because the range is over signed ints break :x math.negateCast(value - end_uint) catch unreachable; }; return result; } else { unreachable; } } else { const total_range = end - start; const leftover = @maxValue(T) % total_range; const upper_bound = @maxValue(T) - leftover; var rand_val_array: [@sizeOf(T)]u8 = undefined; while (true) { r.bytes(rand_val_array[0..]); const rand_val = mem.readInt(rand_val_array, T, builtin.Endian.Little); if (rand_val < upper_bound) { return start + (rand_val % total_range); } } } } /// Return a floating point value evenly distributed in the range [0, 1). pub fn float(r: *Random, comptime T: type) T { // Generate a uniform value between [1, 2) and scale down to [0, 1). // Note: The lowest mantissa bit is always set to 0 so we only use half the available range. switch (T) { f32 => { const s = r.scalar(u32); const repr = (0x7f << 23) | (s >> 9); return @bitCast(f32, repr) - 1.0; }, f64 => { const s = r.scalar(u64); const repr = (0x3ff << 52) | (s >> 12); return @bitCast(f64, repr) - 1.0; }, else => @compileError("unknown floating point type"), } } /// Return a floating point value normally distributed with mean = 0, stddev = 1. /// /// To use different parameters, use: floatNorm(...) * desiredStddev + desiredMean. pub fn floatNorm(r: *Random, comptime T: type) T { const value = ziggurat.next_f64(r, ziggurat.NormDist); switch (T) { f32 => return @floatCast(f32, value), f64 => return value, else => @compileError("unknown floating point type"), } } /// Return an exponentially distributed float with a rate parameter of 1. /// /// To use a different rate parameter, use: floatExp(...) / desiredRate. pub fn floatExp(r: *Random, comptime T: type) T { const value = ziggurat.next_f64(r, ziggurat.ExpDist); switch (T) { f32 => return @floatCast(f32, value), f64 => return value, else => @compileError("unknown floating point type"), } } /// Shuffle a slice into a random order. pub fn shuffle(r: *Random, comptime T: type, buf: []T) void { if (buf.len < 2) { return; } var i: usize = 0; while (i < buf.len - 1) : (i += 1) { const j = r.range(usize, i, buf.len); mem.swap(T, &buf[i], &buf[j]); } } }; // Generator to extend 64-bit seed values into longer sequences. // // The number of cycles is thus limited to 64-bits regardless of the engine, but this // is still plenty for practical purposes. const SplitMix64 = struct { s: u64, pub fn init(seed: u64) SplitMix64 { return SplitMix64{ .s = seed }; } pub fn next(self: *SplitMix64) u64 { self.s +%= 0x9e3779b97f4a7c15; var z = self.s; z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) *% 0x94d049bb133111eb; return z ^ (z >> 31); } }; test "splitmix64 sequence" { var r = SplitMix64.init(0xaeecf86f7878dd75); const seq = []const u64{ 0x5dbd39db0178eb44, 0xa9900fb66b397da3, 0x5c1a28b1aeebcf5c, 0x64a963238f776912, 0xc6d4177b21d1c0ab, 0xb2cbdbdb5ea35394, }; for (seq) |s| { std.debug.assert(s == r.next()); } } // PCG32 - http://www.pcg-random.org/ // // PRNG pub const Pcg = struct { const default_multiplier = 6364136223846793005; random: Random, s: u64, i: u64, pub fn init(init_s: u64) Pcg { var pcg = Pcg{ .random = Random{ .fillFn = fill }, .s = undefined, .i = undefined, }; pcg.seed(init_s); return pcg; } fn next(self: *Pcg) u32 { const l = self.s; self.s = l *% default_multiplier +% (self.i | 1); const xor_s = @truncate(u32, ((l >> 18) ^ l) >> 27); const rot = @intCast(u32, l >> 59); return (xor_s >> @intCast(u5, rot)) | (xor_s << @intCast(u5, (0 -% rot) & 31)); } fn seed(self: *Pcg, init_s: u64) void { // Pcg requires 128-bits of seed. var gen = SplitMix64.init(init_s); self.seedTwo(gen.next(), gen.next()); } fn seedTwo(self: *Pcg, init_s: u64, init_i: u64) void { self.s = 0; self.i = (init_s << 1) | 1; self.s = self.s *% default_multiplier +% self.i; self.s +%= init_i; self.s = self.s *% default_multiplier +% self.i; } fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Pcg, "random", r); var i: usize = 0; const aligned_len = buf.len - (buf.len & 7); // Complete 4 byte segments. while (i < aligned_len) : (i += 4) { var n = self.next(); comptime var j: usize = 0; inline while (j < 4) : (j += 1) { buf[i + j] = @truncate(u8, n); n >>= 8; } } // Remaining. (cuts the stream) if (i != buf.len) { var n = self.next(); while (i < buf.len) : (i += 1) { buf[i] = @truncate(u8, n); n >>= 4; } } } }; test "pcg sequence" { var r = Pcg.init(0); const s0: u64 = 0x9394bf54ce5d79de; const s1: u64 = 0x84e9c579ef59bbf7; r.seedTwo(s0, s1); const seq = []const u32{ 2881561918, 3063928540, 1199791034, 2487695858, 1479648952, 3247963454, }; for (seq) |s| { std.debug.assert(s == r.next()); } } // Xoroshiro128+ - http://xoroshiro.di.unimi.it/ // // PRNG pub const Xoroshiro128 = struct { random: Random, s: [2]u64, pub fn init(init_s: u64) Xoroshiro128 { var x = Xoroshiro128{ .random = Random{ .fillFn = fill }, .s = undefined, }; x.seed(init_s); return x; } fn next(self: *Xoroshiro128) u64 { const s0 = self.s[0]; var s1 = self.s[1]; const r = s0 +% s1; s1 ^= s0; self.s[0] = math.rotl(u64, s0, u8(55)) ^ s1 ^ (s1 << 14); self.s[1] = math.rotl(u64, s1, u8(36)); return r; } // Skip 2^64 places ahead in the sequence fn jump(self: *Xoroshiro128) void { var s0: u64 = 0; var s1: u64 = 0; const table = []const u64{ 0xbeac0467eba5facb, 0xd86b048b86aa9922, }; inline for (table) |entry| { var b: usize = 0; while (b < 64) : (b += 1) { if ((entry & (u64(1) << @intCast(u6, b))) != 0) { s0 ^= self.s[0]; s1 ^= self.s[1]; } _ = self.next(); } } self.s[0] = s0; self.s[1] = s1; } fn seed(self: *Xoroshiro128, init_s: u64) void { // Xoroshiro requires 128-bits of seed. var gen = SplitMix64.init(init_s); self.s[0] = gen.next(); self.s[1] = gen.next(); } fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Xoroshiro128, "random", r); var i: usize = 0; const aligned_len = buf.len - (buf.len & 7); // Complete 8 byte segments. while (i < aligned_len) : (i += 8) { var n = self.next(); comptime var j: usize = 0; inline while (j < 8) : (j += 1) { buf[i + j] = @truncate(u8, n); n >>= 8; } } // Remaining. (cuts the stream) if (i != buf.len) { var n = self.next(); while (i < buf.len) : (i += 1) { buf[i] = @truncate(u8, n); n >>= 8; } } } }; test "xoroshiro sequence" { var r = Xoroshiro128.init(0); r.s[0] = 0xaeecf86f7878dd75; r.s[1] = 0x01cd153642e72622; const seq1 = []const u64{ 0xb0ba0da5bb600397, 0x18a08afde614dccc, 0xa2635b956a31b929, 0xabe633c971efa045, 0x9ac19f9706ca3cac, 0xf62b426578c1e3fb, }; for (seq1) |s| { std.debug.assert(s == r.next()); } r.jump(); const seq2 = []const u64{ 0x95344a13556d3e22, 0xb4fb32dafa4d00df, 0xb2011d9ccdcfe2dd, 0x05679a9b2119b908, 0xa860a1da7c9cd8a0, 0x658a96efe3f86550, }; for (seq2) |s| { std.debug.assert(s == r.next()); } } // ISAAC64 - http://www.burtleburtle.net/bob/rand/isaacafa.html // // CSPRNG // // Follows the general idea of the implementation from here with a few shortcuts. // https://doc.rust-lang.org/rand/src/rand/prng/isaac64.rs.html pub const Isaac64 = struct { random: Random, r: [256]u64, m: [256]u64, a: u64, b: u64, c: u64, i: usize, pub fn init(init_s: u64) Isaac64 { var isaac = Isaac64{ .random = Random{ .fillFn = fill }, .r = undefined, .m = undefined, .a = undefined, .b = undefined, .c = undefined, .i = undefined, }; // seed == 0 => same result as the unseeded reference implementation isaac.seed(init_s, 1); return isaac; } fn step(self: *Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void { const x = self.m[base + m1]; self.a = mix +% self.m[base + m2]; const y = self.a +% self.b +% self.m[(x >> 3) % self.m.len]; self.m[base + m1] = y; self.b = x +% self.m[(y >> 11) % self.m.len]; self.r[self.r.len - 1 - base - m1] = self.b; } fn refill(self: *Isaac64) void { const midpoint = self.r.len / 2; self.c +%= 1; self.b +%= self.c; { var i: usize = 0; while (i < midpoint) : (i += 4) { self.step(~(self.a ^ (self.a << 21)), i + 0, 0, midpoint); self.step(self.a ^ (self.a >> 5), i + 1, 0, midpoint); self.step(self.a ^ (self.a << 12), i + 2, 0, midpoint); self.step(self.a ^ (self.a >> 33), i + 3, 0, midpoint); } } { var i: usize = 0; while (i < midpoint) : (i += 4) { self.step(~(self.a ^ (self.a << 21)), i + 0, midpoint, 0); self.step(self.a ^ (self.a >> 5), i + 1, midpoint, 0); self.step(self.a ^ (self.a << 12), i + 2, midpoint, 0); self.step(self.a ^ (self.a >> 33), i + 3, midpoint, 0); } } self.i = 0; } fn next(self: *Isaac64) u64 { if (self.i >= self.r.len) { self.refill(); } const value = self.r[self.i]; self.i += 1; return value; } fn seed(self: *Isaac64, init_s: u64, comptime rounds: usize) void { // We ignore the multi-pass requirement since we don't currently expose full access to // seeding the self.m array completely. mem.set(u64, self.m[0..], 0); self.m[0] = init_s; // prescrambled golden ratio constants var a = []const u64{ 0x647c4677a2884b7c, 0xb9f8b322c73ac862, 0x8c0ea5053d4712a0, 0xb29b2e824a595524, 0x82f053db8355e0ce, 0x48fe4a0fa5a09315, 0xae985bf2cbfc89ed, 0x98f5704f6c44c0ab, }; comptime var i: usize = 0; inline while (i < rounds) : (i += 1) { var j: usize = 0; while (j < self.m.len) : (j += 8) { comptime var x1: usize = 0; inline while (x1 < 8) : (x1 += 1) { a[x1] +%= self.m[j + x1]; } a[0] -%= a[4]; a[5] ^= a[7] >> 9; a[7] +%= a[0]; a[1] -%= a[5]; a[6] ^= a[0] << 9; a[0] +%= a[1]; a[2] -%= a[6]; a[7] ^= a[1] >> 23; a[1] +%= a[2]; a[3] -%= a[7]; a[0] ^= a[2] << 15; a[2] +%= a[3]; a[4] -%= a[0]; a[1] ^= a[3] >> 14; a[3] +%= a[4]; a[5] -%= a[1]; a[2] ^= a[4] << 20; a[4] +%= a[5]; a[6] -%= a[2]; a[3] ^= a[5] >> 17; a[5] +%= a[6]; a[7] -%= a[3]; a[4] ^= a[6] << 14; a[6] +%= a[7]; comptime var x2: usize = 0; inline while (x2 < 8) : (x2 += 1) { self.m[j + x2] = a[x2]; } } } mem.set(u64, self.r[0..], 0); self.a = 0; self.b = 0; self.c = 0; self.i = self.r.len; // trigger refill on first value } fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Isaac64, "random", r); var i: usize = 0; const aligned_len = buf.len - (buf.len & 7); // Fill complete 64-byte segments while (i < aligned_len) : (i += 8) { var n = self.next(); comptime var j: usize = 0; inline while (j < 8) : (j += 1) { buf[i + j] = @truncate(u8, n); n >>= 8; } } // Fill trailing, ignoring excess (cut the stream). if (i != buf.len) { var n = self.next(); while (i < buf.len) : (i += 1) { buf[i] = @truncate(u8, n); n >>= 8; } } } }; test "isaac64 sequence" { var r = Isaac64.init(0); // from reference implementation const seq = []const u64{ 0xf67dfba498e4937c, 0x84a5066a9204f380, 0xfee34bd5f5514dbb, 0x4d1664739b8f80d6, 0x8607459ab52a14aa, 0x0e78bc5a98529e49, 0xfe5332822ad13777, 0x556c27525e33d01a, 0x08643ca615f3149f, 0xd0771faf3cb04714, 0x30e86f68a37b008d, 0x3074ebc0488a3adf, 0x270645ea7a2790bc, 0x5601a0a8d3763c6a, 0x2f83071f53f325dd, 0xb9090f3d42d2d2ea, }; for (seq) |s| { std.debug.assert(s == r.next()); } } // Actual Random helper function tests, pcg engine is assumed correct. test "Random float" { var prng = DefaultPrng.init(0); var i: usize = 0; while (i < 1000) : (i += 1) { const val1 = prng.random.float(f32); std.debug.assert(val1 >= 0.0); std.debug.assert(val1 < 1.0); const val2 = prng.random.float(f64); std.debug.assert(val2 >= 0.0); std.debug.assert(val2 < 1.0); } } test "Random scalar" { var prng = DefaultPrng.init(0); const s = prng.random.scalar(u64); } test "Random bytes" { var prng = DefaultPrng.init(0); var buf: [2048]u8 = undefined; prng.random.bytes(buf[0..]); } test "Random shuffle" { var prng = DefaultPrng.init(0); var seq = []const u8{ 0, 1, 2, 3, 4 }; var seen = []bool{false} ** 5; var i: usize = 0; while (i < 1000) : (i += 1) { prng.random.shuffle(u8, seq[0..]); seen[seq[0]] = true; std.debug.assert(sumArray(seq[0..]) == 10); } // we should see every entry at the head at least once for (seen) |e| { std.debug.assert(e == true); } } fn sumArray(s: []const u8) u32 { var r: u32 = 0; for (s) |e| r += e; return r; } test "Random range" { var prng = DefaultPrng.init(0); testRange(&prng.random, -4, 3); testRange(&prng.random, -4, -1); testRange(&prng.random, 10, 14); } fn testRange(r: *Random, start: i32, end: i32) void { const count = @intCast(usize, end - start); var values_buffer = []bool{false} ** 20; const values = values_buffer[0..count]; var i: usize = 0; while (i < count) { const value = r.range(i32, start, end); const index = @intCast(usize, value - start); if (!values[index]) { i += 1; values[index] = true; } } }
std/rand/index.zig
const std = @import("std"); const runtime_spec = @import("runtime_spec.zig"); const syscall = @import("syscall.zig"); const utils = @import("utils.zig"); const linux = std.os.linux; const RootfsSetupError = error{ MountParentPrivateFailed, InvalidDeviceType, InvalidRootfsPropagation }; fn makeParentMountPrivate(alloc: *std.mem.Allocator, rootfs: [:0]const u8) !void { var arena = std.heap.ArenaAllocator.init(alloc); defer arena.deinit(); var parent = try arena.allocator.dupeZ(u8, rootfs); while (true) { if (syscall.mount(null, parent, null, linux.MS.PRIVATE, null)) |_| { return; } else |_| if (std.fs.path.dirname(parent)) |dir| { parent[dir.len] = 0; parent = parent[0..dir.len :0]; } else { return RootfsSetupError.MountParentPrivateFailed; } } unreachable(); } fn prepare(alloc: *std.mem.Allocator, rootfs: [:0]const u8) !void { try makeParentMountPrivate(alloc, rootfs); try syscall.mount(rootfs, rootfs, null, linux.MS.BIND | linux.MS.REC, null); try syscall.mount(null, rootfs, null, linux.MS.PRIVATE, null); } fn updateMountFlags(current_flags: u32, name: []const u8) ?u32 { if (std.mem.eql(u8, name, "bind")) return current_flags | linux.MS.BIND; if (std.mem.eql(u8, name, "rbind")) return current_flags | linux.MS.REC | linux.MS.BIND; if (std.mem.eql(u8, name, "ro")) return current_flags | linux.MS.RDONLY; if (std.mem.eql(u8, name, "rw")) return current_flags & ~@intCast(u32, linux.MS.RDONLY); if (std.mem.eql(u8, name, "suid")) return current_flags & ~@intCast(u32, linux.MS.NOSUID); if (std.mem.eql(u8, name, "nosuid")) return current_flags | linux.MS.NOSUID; if (std.mem.eql(u8, name, "dev")) return current_flags & ~@intCast(u32, linux.MS.NODEV); if (std.mem.eql(u8, name, "nodev")) return current_flags | linux.MS.NODEV; if (std.mem.eql(u8, name, "exec")) return current_flags & ~@intCast(u32, linux.MS.NOEXEC); if (std.mem.eql(u8, name, "noexec")) return current_flags | linux.MS.NOEXEC; if (std.mem.eql(u8, name, "sync")) return current_flags | linux.MS.SYNCHRONOUS; if (std.mem.eql(u8, name, "async")) return current_flags & ~@intCast(u32, linux.MS.SYNCHRONOUS); if (std.mem.eql(u8, name, "dirsync")) return current_flags | linux.MS.DIRSYNC; if (std.mem.eql(u8, name, "remount")) return current_flags | linux.MS.REMOUNT; if (std.mem.eql(u8, name, "mand")) return current_flags | linux.MS.MANDLOCK; if (std.mem.eql(u8, name, "nomand")) return current_flags & ~@intCast(u32, linux.MS.MANDLOCK); if (std.mem.eql(u8, name, "atime")) return current_flags & ~@intCast(u32, linux.MS.NOATIME); if (std.mem.eql(u8, name, "noatime")) return current_flags | linux.MS.NOATIME; if (std.mem.eql(u8, name, "diratime")) return current_flags & ~@intCast(u32, linux.MS.NODIRATIME); if (std.mem.eql(u8, name, "nodiratime")) return current_flags | linux.MS.NODIRATIME; if (std.mem.eql(u8, name, "relatime")) return current_flags | linux.MS.RELATIME; if (std.mem.eql(u8, name, "norelatime")) return current_flags & ~@intCast(u32, linux.MS.RELATIME); if (std.mem.eql(u8, name, "strictatime")) return current_flags | linux.MS.STRICTATIME; if (std.mem.eql(u8, name, "nostrictatime")) return current_flags & ~@intCast(u32, linux.MS.STRICTATIME); if (std.mem.eql(u8, name, "shared")) return current_flags | linux.MS.SHARED; if (std.mem.eql(u8, name, "rshared")) return current_flags | linux.MS.REC | linux.MS.SHARED; if (std.mem.eql(u8, name, "slave")) return current_flags | linux.MS.SLAVE; if (std.mem.eql(u8, name, "rslave")) return current_flags | linux.MS.REC | linux.MS.SLAVE; if (std.mem.eql(u8, name, "private")) return current_flags | linux.MS.PRIVATE; if (std.mem.eql(u8, name, "rprivate")) return current_flags | linux.MS.REC | linux.MS.PRIVATE; if (std.mem.eql(u8, name, "unbindable")) return current_flags | linux.MS.UNBINDABLE; if (std.mem.eql(u8, name, "runbindable")) return current_flags | linux.MS.REC | linux.MS.UNBINDABLE; return null; } fn doMounts(alloc: *std.mem.Allocator, rootfs: [:0]const u8, mounts: []runtime_spec.Mount) !void { for (mounts) |m| { var arena = std.heap.ArenaAllocator.init(alloc); defer arena.deinit(); var flags: u32 = 0; var opts = try std.ArrayList([]const u8).initCapacity(&arena.allocator, m.options.len); for (m.options) |opt| { if (updateMountFlags(flags, opt)) |new_flags| { flags = new_flags; } else { opts.appendAssumeCapacity(opt); } } const dest = try std.fs.path.join(&arena.allocator, &[_][]const u8{ rootfs, m.destination }); try utils.mkdirs(dest, 0o755); try syscall.mount( try arena.allocator.dupeZ(u8, m.source), try arena.allocator.dupeZ(u8, dest), try arena.allocator.dupeZ(u8, m.type), flags, @ptrCast(*u8, try std.mem.joinZ(&arena.allocator, ",", opts.items)), ); } } const DeviceType = enum(u8) { BlockDevice = 'b', CharDevice = 'c', FifoDevice = 'p', _, }; fn getDeviceFileModeFromType(device_type: []u8) RootfsSetupError!u32 { if (device_type.len != 1) { return error.InvalidDeviceType; } return switch (@intToEnum(DeviceType, device_type[0])) { .BlockDevice => linux.S.IFBLK, .CharDevice => linux.S.IFCHR, .FifoDevice => linux.S.IFIFO, _ => error.InvalidDeviceType, }; } fn createDevices(alloc: *std.mem.Allocator, rootfs: [:0]const u8, devices: []runtime_spec.LinuxDevice) !void { for (devices) |d| { var arena = std.heap.ArenaAllocator.init(alloc); defer arena.deinit(); const dest = try std.fs.path.joinZ(&arena.allocator, &[_][]const u8{ rootfs, d.path }); const file_mode: linux.mode_t = d.fileMode | try getDeviceFileModeFromType(d.type); const dev = syscall.mkdev(d.major, d.minor); try syscall.mknod(dest, file_mode, dev); try syscall.chown(dest, d.uid, d.gid); } } fn moveChroot(rootfs: [:0]const u8) !void { try std.os.chdir(rootfs); try syscall.mount(rootfs, "/", null, linux.MS.MOVE, null); try syscall.chroot("."); try std.os.chdir("/"); } pub fn setup(alloc: *std.mem.Allocator, spec: *const runtime_spec.Spec) !void { var arena = std.heap.ArenaAllocator.init(alloc); defer arena.deinit(); const rootfs = try utils.realpathAllocZ(&arena.allocator, spec.root.path); // Remount old rootfs before we preparing new rootfs to prevent leaking mounts outside namespace var rootfs_propagation: u32 = linux.MS.REC | linux.MS.PRIVATE; if (spec.linux.rootfsPropagation) |propagation| { rootfs_propagation = updateMountFlags(0, propagation) orelse 0; } if (rootfs_propagation & (linux.MS.SHARED | linux.MS.SLAVE | linux.MS.PRIVATE | linux.MS.UNBINDABLE) == 0) { return RootfsSetupError.InvalidRootfsPropagation; } try syscall.mount(null, "/", null, rootfs_propagation, null); try prepare(alloc, rootfs); try doMounts(alloc, rootfs, spec.mounts); try createDevices(alloc, rootfs, spec.linux.devices); try moveChroot(rootfs); if (spec.root.readonly) { try syscall.mount(null, "/", null, linux.MS.REMOUNT | linux.MS.BIND | linux.MS.RDONLY, null); } }
src/rootfs.zig
const std = @import("std"); const mem = std.mem; const atomic = std.atomic; const maxInt = std.math.maxInt; const SpinFutex = struct { // spin-lock pub fn wait(ptr: *const atomic.Atomic(u32), expect: u32, comptime timeout: ?u64) error{TimedOut}!void { if (timeout) |_| @compileError("Not implemented!"); while (ptr.load(.Unordered) == expect) { std.os.sched_yield() catch std.atomic.spinLoopHint(); } } pub fn wake(ptr: *const atomic.Atomic(u32), num_waiters: u32) void { _ = ptr; _ = num_waiters; } }; //const Futex = SpinFutex; const Futex = std.Thread.Futex; const nnet = @import("nnet.zig"); // multithreaded nnet trainer pub fn forNet(NNet: anytype) type { return struct { const Self = @This(); pub const Float = NNet.ValType; pub const TestCase = nnet.typed(NNet.ValType).TestCase(NNet.input_len, NNet.output_len); pub const TestAccessor = nnet.typed(NNet.ValType).TestAccessor(TestCase); const log = std.log.scoped(.NNetTrainer); // cordinates workers and work to be done const WorkQueue = struct { const stop = maxInt(u32); const start = stop - 1; inputs: []u32 = undefined, next_input: atomic.Atomic(u32) = .{ .value = start }, results_done: atomic.Atomic(u32) = .{ .value = 0 }, results_mutex: std.Thread.Mutex = .{}, results: NNet.TrainResult = .{}, }; alloc: *mem.Allocator, rnd: *std.rand.Random, batch_size: usize = 4, learn_rate: Float = 0.1, epoch_idx: usize = 0, workers: usize = 8, // private - used to coordinate threads pub fn init(alloc: *mem.Allocator, rnd: *std.rand.Random) Self { return .{ .alloc = alloc, .rnd = rnd, }; } fn worker(wq: *WorkQueue, inp_nnet: *NNet, tacc: *TestAccessor) void { @setFloatMode(std.builtin.FloatMode.Optimized); var net = inp_nnet; var r: NNet.TrainResult = .{}; Futex.wait(&wq.next_input, WorkQueue.start, null) catch unreachable; var inputs : []u32 = wq.inputs; main_worker_loop: while (true) { var input_idx = wq.next_input.fetchAdd(1, atomic.Ordering.AcqRel); if (input_idx < inputs.len) { //var timer = std.time.Timer.start() catch unreachable; var test_case = tacc.grabTest(inputs[input_idx]); defer tacc.freeTest(test_case); net.trainDeriv(test_case.*, &r); //std.debug.print("trainDeriv: {}\n", .{std.fmt.fmtDuration(timer.lap())}); } else { // no more inputs if (r.test_cases > 0) { // merge whats left of results var lock = wq.results_mutex.acquire(); wq.results.merge(r); var total = wq.results.test_cases; lock.release(); var total_i: u32 = @floatToInt(u32, total); wq.results_done.store(total_i, .Release); if (total_i == @intCast(u32, inputs.len)) { Futex.wake(&wq.results_done, maxInt(u32)); //log.info("wake: {}", .{total_i}); } // else log.info("NO wake: {}", .{total_i}); r = .{}; // fresh working copy } { // go to sleep var inp: u32 = wq.next_input.load(.Acquire); while (inp >= inputs.len) { if (inp == WorkQueue.stop) { break :main_worker_loop; // all done - exit } Futex.wait(&wq.next_input, inp, null) catch unreachable; if (input_idx > wq.next_input.load(atomic.Ordering.Acquire)) break; inp = wq.next_input.load(.Acquire); } } // prep for work net = inp_nnet; // copy fresh working copy inputs = wq.inputs; } } } pub fn trainEpoches(self: *Self, net: *NNet, test_accesor: *TestAccessor, epoches: u32) !void { @setFloatMode(std.builtin.FloatMode.Optimized); const workers: usize = @minimum(self.workers, self.batch_size); if (workers < 1 or workers > 1024) std.debug.panic("Invalid worker count: {}", .{workers}); std.debug.print("Epoch {} started (batchsize: {}, threads: {})\n", .{ self.epoch_idx, self.batch_size, self.workers }); var timer = try std.time.Timer.start(); const test_len: usize = test_accesor.testCount(); // TODO: move as struct member to avoid allocating for each epoch var shuffled: []u32 = try self.alloc.alloc(u32, test_len); defer self.alloc.free(shuffled); for (shuffled) |*e, idx| { e.* = @intCast(u32,idx); } var wq = try self.alloc.create(WorkQueue); defer self.alloc.destroy(wq); wq.* = .{}; var threads = try self.alloc.alloc(std.Thread, workers); defer self.alloc.free(threads); for (threads) |*t| t.* = try std.Thread.spawn(.{ .stack_size = 1671168 + @sizeOf(NNet) }, worker, .{ wq, net, test_accesor}); var print_timer = try std.time.Timer.start(); var epoch_i: u32 = 0; while (epoch_i < epoches) : (epoch_i += 1) { defer self.epoch_idx += 1; { // shuffle var st = try std.time.Timer.start(); self.rnd.shuffle(@TypeOf(shuffled[0]), shuffled); log.info("Shuffle time: {}", .{std.fmt.fmtDuration(st.read())}); } wq.* = .{}; var correct: u32 = 0.0; var loss: Float = 0.0; var bb: usize = 0; while (bb < test_len) : (bb += self.batch_size) { const batch = shuffled[bb..@minimum(bb + self.batch_size, test_len)]; var lock = wq.results_mutex.tryAcquire(); if (lock) |l| { wq.results = .{}; l.release(); } else @panic("Threading error: someone has grabbed results lock!"); wq.results_done.store(0, .Release); wq.inputs = batch; wq.next_input.store(@intCast(u32, 0), .Release); Futex.wake(&wq.next_input, maxInt(u32)); // wake workers // wait for result var expect_res: u32 = 0; while (expect_res != batch.len) { Futex.wait(&wq.results_done, expect_res, null) catch unreachable; expect_res = wq.results_done.load(.Acquire); //log.info("Results: {}", .{expect_res}); } // update nnet // note: we don't lock wq.results as at this point workers are sleeping if (@floatToInt(usize, wq.results.test_cases) != batch.len) std.debug.panic("Bad threading - result count doesn't match expected batch size! {}/{}", .{ @floatToInt(usize, wq.results.test_cases), batch.len }); //wq.results.average(); net.learn(wq.results, self.learn_rate); if (!std.math.isFinite(wq.results.loss)) { log.alert("Batch {}# loss not finite! {}", .{bb, wq.results.loss}); //wq.results.print(); std.os.abort(); } loss += wq.results.loss; correct += wq.results.correct; if (print_timer.read() > 50 * 1000 * 1000) { print_timer.reset(); const acc = 100 * @intToFloat(Float, wq.results.correct) / @intToFloat(Float, batch.len); log.info("Batch {}# loss: {d:.4} accuracy: {d:.2}%", .{ bb / self.batch_size, wq.results.loss, acc }); } } // print stats const accuracy = @intToFloat(Float, correct) / @intToFloat(Float, test_len); log.notice("Epoch {}# train time: {} avg loss: {d:.4} accuracy: {d:.2}%\n", .{ self.epoch_idx, std.fmt.fmtDuration(timer.lap()), loss / @intToFloat(Float, test_len), accuracy * 100 }); } // stop workers wq.next_input.store(WorkQueue.stop, .SeqCst); Futex.wake(&wq.next_input, maxInt(u32)); for (threads) |t| t.join(); } }; }
src/nnet_trainer.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day01.txt"); pub fn main() !void { try partOne(); try partTwo(); } /// Iterate through the tokens and compare the previous value with the /// current value pub fn partOne() !void { var tokens = tokenize(u8, data, "\n"); var total_increases: u32 = 0; var previous: u32 = undefined; while (try getNextInt(&tokens)) |token| { if (previous != 0 and previous < token) { total_increases += 1; } previous = token; } std.log.info("Total is {}", .{total_increases}); } /// Iterate through the tokens as a "sliding window" /// where we sum up every three tokens /// I use a buffer to store the three values to add /// After each loop iteration, the oldest value in the buffer /// is replaced with the newest one by using the modulus pub fn partTwo() !void { var tokens = tokenize(u8, data, "\n"); var buffer = [_]u32{ (try getNextInt(&tokens)).?, (try getNextInt(&tokens)).?, (try getNextInt(&tokens)).?, }; var previous_sum = sum(&buffer); var next: usize = 0; var total_increases: u32 = 0; while (try getNextInt(&tokens)) |token| { buffer[next] = token; next += 1; next %= buffer.len; var new_sum = sum(&buffer); if (previous_sum < new_sum) { total_increases += 1; } previous_sum = new_sum; } std.log.info("Total is {}", .{total_increases}); } fn getNextInt(tokens: *std.mem.TokenIterator(u8)) !?u32 { if (tokens.next()) |value| { return try parseInt(u32, value, 10); } return null; } fn sum(buffer: []u32) u32 { var total: u32 = 0; for (buffer) |value| { total += value; } return total; } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day01.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const meta = std.meta; const builtin = std.builtin; const Comparable = @import("comparable.zig"); const option = @This(); /// some type that is a liite bit like rust's optional type /// I do this just to get rid of if(something != null) /// and don't want to see some error messages like /// xxx type not supported member access because is a optional /// sometime I just want to .expect("get a null xxx"); /// if you like to handle null by you self /// and you know every optional value's ownership /// you can skip this type and use the zig original optional type /// this type is experimental and may contains some bugs /// help me to make it better! /// not having unwrap_unchecked /// just because every unwrap operations here are unchecked /// no as_pin_ref or as_pin_mut /// cause zig's async runtime is not the same /// no ok_or or ok_or_else or some other thing to converts to Result type pub fn Option(comptime T: type) type { return struct { /// for hidding memory operations /// I specified the allocator for this type /// in future versions I will implement a general one for this type const allocator: Allocator = std.heap.page_allocator; const Self = @This(); const ComparedResult = Comparable.ComparedResult; /// it just wrapping around a optional type /// but this memory's ownership is holded by the type value: ?*T, /// zig's error handling is different /// so I put the errors here /// also as you can see /// this kind of error handling /// Result type could not be implemented here pub const Error = error{ UnhandledNullValue, MappingWithInvalidFunctionOrNotFunction, }; /// exactly works the same as the outside one pub fn Some(value: T) !Option(T) { var ptr = try Self.allocator.create(T); ptr.* = value; return Self{ .value = ptr }; } /// the none value /// just a ownership upon null value pub const None = Self{ .value = null }; /// Returns true if the option is a Some value. pub fn is_some(self: *const Self) bool { return !self.is_none(); } /// Returns true if the option is a None value. pub fn is_none(self: *const Self) bool { return self.value == null; } /// Returns true if the option is a Some value containing the given value. pub fn contains(self: *Self, x: *T) bool { if (self.is_none()) return false; return self.value.?.* == x.*; } /// this gives only const pointer /// exactly like the borrow in rust pub fn as_ref(self: *const Self) !Option(*const T) { if (self.is_none()) return Option(*const T).None; return try Option(*const T).Some(&self.value.?.*); } /// this will give the mutiable pointer to inner value /// but because zig does not check multithread safety /// this may not works the same as rust's pub fn as_mut(self: *Self) !Option(*T) { if (self.is_none()) return Option(*T).None; return try Option(*T).Some(self.value.?); } /// Returns the contained Some value, consuming the self value. /// PS: this will drop the inner value's memory address /// any optional around this type may cause undefined behavior pub fn expect(self: *Self, msg: anyerror) !T { if (self.is_none()) return msg; var res = self.value.?.*; self.deinit(); return res; } /// Returns the contained Some value, consuming the self value. /// Because this function may panic, its use is generally discouraged. /// Instead, prefer to use pattern matching and handle the None case explicitly, /// or call unwrap_or, unwrap_or_else, or unwrap_or_default. /// PS: this will drop the inner value's memory address /// any optional around this type may cause undefined behavior pub fn unwrap(self: *Self) !T { return self.expect(Self.Error.UnhandledNullValue); } /// Returns the contained Some value or a provided default. /// Arguments passed to unwrap_or are eagerly evaluated; /// if you are passing the result of a function call, /// it is recommended to use unwrap_or_else, which is lazily evaluated. /// PS: this will drop the inner value's memory address /// any optional around this type may cause undefined behavior pub fn unwrap_or(self: *Self, default: T) T { if (self.is_none()) return default; var res = self.value.?.*; self.deinit(); return res; } /// Returns the contained Some value or computes it from a function. /// zig not having closure right now, but we can use function pointer /// it should works the same but just a little waste of memory /// PS: this will drop the inner value's memory address /// any optional around this type may cause undefined behavior pub fn unwrap_or_else(self: *Self, f: fn () T) T { if (self.is_none()) return f(); var res = self.value.?.*; self.deinit(); return res; } /// Maps an Option<T> to Option<U> by applying a function to a contained value. /// this really takes a litte bit time to found implementation for this /// it may not looks like a right implementation /// but it works kind well /// this operation will not change anything inside this type /// the function gives here also not have the chance to change the inner value /// even when it can, the value it got is a temporary value pub fn map(self: *Self, f: anytype) !Option(@typeInfo(@TypeOf(f)).Fn.return_type.?) { if (@typeInfo(@TypeOf(f)).Fn.args.len == 1) { if (self.is_none()) return Self.Error.UnhandledNullValue; var value_cloned = try Self.allocator.create(T); value_cloned.* = self.value.?.*; var output = f(value_cloned.*); var res = try Option(@TypeOf(output)).Some(output); Self.allocator.destroy(value_cloned); return res; } else { return Self.Error.MappingWithInvalidFunctionOrNotFunction; } } /// Returns the provided default result (if none), /// or applies a function to the contained value (if any). /// Arguments passed to map_or are eagerly evaluated; /// if you are passing the result of a function call, /// it is recommended to use map_or_else, which is lazily evaluated. /// same rule as the map one pub fn map_or(self: *Self, f: anytype, default: @typeInfo(@TypeOf(f)).Fn.return_type.?) !@typeInfo(@TypeOf(f)).Fn.return_type.? { if (self.is_none()) return default; return (try self.map(f)).unwrap(); } /// Computes a default function result (if none), /// or applies a different function to the contained value (if any). /// also the same rule as the map one pub fn map_or_else(self: *Self, f: anytype, default: fn () @typeInfo(@TypeOf(f)).Fn.return_type.?) !@typeInfo(@TypeOf(f)).Fn.return_type.? { if (self.is_none()) return default(); return (try self.map(f)).unwrap(); } /// zig not having auto drop /// so we need to drop it ourselves pub fn deinit(self: *Self) void { if (self.is_some()) Self.allocator.destroy(self.value.?); self.value = null; } // try to implement a comparable for Option type // inner type is must be comparable or implement Comparable pub fn cmp(self: *Self, other: Self) Self.ComparedResult { if (self.is_none()) return Self.ComparedResult.Less; var value = self.value.?.*; var othervalue = other.value.?.*; switch (@typeInfo(@TypeOf(value))) { .Float, .Int => { if (value == othervalue) return Self.ComparedResult.Equal; if (value < othervalue) return Self.ComparedResult.Less; if (value > othervalue) return Self.ComparedResult.Greater; }, .Struct => { if (@TypeOf(value) == Comparable) { return value.cmp(othervalue); } else { std.log.warn("struct type {s} is not implemented comparable", .{@TypeOf(value)}); } }, .Pointer => { var res = std.cstr.cmp(value, othervalue); if(res == 0) return Self.ComparedResult.Equal; if(res == 1) return Self.ComparedResult.Greater; if(res == -1) return Self.ComparedResult.Less; }, else => { std.log.warn("type {s} are not comparable", .{@typeInfo(@TypeOf(value))}); }, } return Self.ComparedResult.NotComparable; } pub fn from(optional: ?*T) Self { return Self{ .value = optional }; } }; } const OptionI32 = Option(i32); test "Some and None" { var i: i32 = 2; var a = try OptionI32.Some(i); a.deinit(); a = OptionI32.None; } test "is_some and is_none" { var i: i32 = 2; var a = try OptionI32.Some(i); try testing.expect(a.is_some()); a.deinit(); a = OptionI32.None; try testing.expect(a.is_none()); } test "contains" { var i: i32 = 2; var j: i32 = 2; var a = try OptionI32.Some(i); try testing.expect(a.contains(&j)); a.deinit(); a = OptionI32.None; try testing.expect(!a.contains(&j)); } test "as_ref" { var i: i32 = 2; var a = try OptionI32.Some(i); defer a.deinit(); var b = try (try a.as_ref()).unwrap(); try testing.expect(b.* == 2); } test "as_mut" { var i: i32 = 2; var a = try OptionI32.Some(i); defer a.deinit(); var b = try (try a.as_mut()).unwrap(); b.* = 3; var c = try (try a.as_ref()).unwrap(); try testing.expect(c.* == 3); } fn ff() *const i32 { var res: i32 = 2; return &res; } test "unwraps" { var i: i32 = 2; var a = OptionI32.None; defer a.deinit(); var b = (try a.as_ref()).unwrap_or(&i); try testing.expect(b.* == i); var c = (try a.as_ref()).unwrap_or_else(ff); try testing.expect(c.* == 2); } fn defaultF() i32 { var res: i32 = 2; return res; } fn mapping(input: i32) i32 { return input + 1; } test "maps" { var i: i32 = 2; var a = try OptionI32.Some(i); var b = try a.map(mapping); try testing.expect((try b.unwrap()) == i + 1); a.deinit(); a = OptionI32.None; var c = try a.map_or(mapping, i); try testing.expect(c == i); var d = OptionI32.None; var e = try d.map_or_else(mapping, defaultF); try testing.expect(e == i); }
src/option.zig
const std = @import("std"); const c = @cImport({ @cInclude("time.h"); }); /// get time in ms pub fn getTime() u64 { var time = std.time.milliTimestamp(); if(time < 0) time = 0; // if your system time is before the beginning of the universe, too bad. return @intCast(u64, time); } /// get start of day in utc using time.h gmtime/timegm pub fn getDayStart(time: u64) u64 { const timeSec: c.time_t = @intCast(c.time_t, time / 1000); var timeInfo = c.gmtime(&timeSec); timeInfo.*.tm_hour = 0; timeInfo.*.tm_min = 0; timeInfo.*.tm_sec = 0; const dayStartSec: u64 = @intCast(u64, c.timegm(timeInfo)); return dayStartSec * 1000; } /// get the time since the start of the day pub fn msSinceDayStart(timeMs: u64) u64 { const dayStart = getDayStart(timeMs); const msSinceDayStartV = timeMs -% dayStart; return msSinceDayStartV; } /// convert ms time to tenhourtime pub fn tenHourTime(msSinceDayStartV: u64) u64 { const floatMsSinceDayStart: f64 = @intToFloat(f64, msSinceDayStartV); const number: f64 = (24.0 * 60.0 * 60.0 * 1000.0) / 100000000.0; return @floatToInt(u64, floatMsSinceDayStart / number); } pub const TenHourTime = struct { LL: u32, cc: u8, ii: u8, qm: u16, pub fn format(timeData: *const TenHourTime, comptime fmt: []const u8, options: std.fmt.FormatOptions, out: var) !void { return std.fmt.format(out, "{:0>2}.{:0>1}LL {:0>2}.{:0>3}ii", .{ timeData.LL, timeData.cc, timeData.ii, timeData.qm }); } }; /// seperate out tenhourtime into LL,cc,ii,qm pub fn formatTime(tht: u64) TenHourTime { return .{ .LL = @intCast(u32, (tht / 1000000) % 100), .cc = @intCast(u8, (tht / 100000) % 10), .ii = @intCast(u8, (tht / 1000) % 100), .qm = @intCast(u16, (tht / 1) % 1000), }; } test "the time is correct" { var value = formatTime(tenHourTime(timeSinceDayStart(1581354755886))); std.testing.expect(value.LL == 71); std.testing.expect(value.cc == 7); std.testing.expect(value.ii == 08); std.testing.expect(value.qm == 201); }
src/tenhourtime.zig
const std = @import("std"); const version = @import("version"); const tar = @import("tar"); const zzz = @import("zzz"); const Dependency = @import("Dependency.zig"); const Package = @import("Package.zig"); const utils = @import("utils.zig"); const curl = @import("curl"); const Allocator = std.mem.Allocator; const Fifo = std.fifo.LinearFifo(u8, .{ .Dynamic = {} }); pub fn getLatest( allocator: Allocator, repository: []const u8, user: []const u8, package: []const u8, range: ?version.Range, ) !version.Semver { const url = if (range) |r| try std.fmt.allocPrintZ(allocator, "https://{s}/pkgs/{s}/{s}/latest?v={u}", .{ repository, user, package, r, }) else try std.fmt.allocPrintZ(allocator, "https://{s}/pkgs/{s}/{s}/latest", .{ repository, user, package, }); defer allocator.free(url); var fifo = Fifo.init(allocator); defer fifo.deinit(); const easy = try curl.Easy.init(); defer easy.cleanup(); try easy.setUrl(url); try easy.setSslVerifyPeer(false); try easy.setWriteFn(curl.writeToFifo(Fifo)); try easy.setWriteData(&fifo); try easy.perform(); const status_code = try easy.getResponseCode(); switch (status_code) { 200 => {}, 404 => { if (range) |r| { std.log.err("failed to find {} for {s}/{s} on {s}", .{ r, user, package, repository, }); } else { std.log.err("failed to find latest for {s}/{s} on {s}", .{ user, package, repository, }); } return error.Explained; }, else => { const stderr = std.io.getStdErr().writer(); try stderr.print("got http status code for {s}: {}", .{ url, status_code }); try stderr.print("{s}\n", .{fifo.readableSlice(0)}); return error.Explained; }, } return version.Semver.parse(fifo.readableSlice(0)); } pub const XferCtx = struct { cb: curl.XferInfoFn, data: ?*anyopaque, }; pub fn getPkg( allocator: Allocator, repository: []const u8, user: []const u8, package: []const u8, semver: version.Semver, dir: std.fs.Dir, xfer_ctx: ?XferCtx, ) !void { const url = try std.fmt.allocPrintZ( allocator, "https://{s}/archive/{s}/{s}/{}", .{ repository, user, package, semver, }, ); defer allocator.free(url); try getTarGz(allocator, url, dir, xfer_ctx); } // not a super huge fan of allocating the entire response over streaming, but // it'll do for now, at least it's compressed lol fn getTarGzImpl( allocator: Allocator, url: [:0]const u8, dir: std.fs.Dir, skip_depth: usize, xfer: ?XferCtx, ) !void { var fifo = Fifo.init(allocator); defer fifo.deinit(); var headers = curl.HeaderList.init(); defer headers.freeAll(); try headers.append("Accept: */*"); const easy = try curl.Easy.init(); defer easy.cleanup(); try easy.setUrl(url); try easy.setHeaders(headers); try easy.setSslVerifyPeer(false); try easy.setWriteFn(curl.writeToFifo(Fifo)); try easy.setWriteData(&fifo); if (xfer) |x| { try easy.setXferInfoFn(x.cb); if (x.data) |data| try easy.setXferInfoData(data); try easy.setNoProgress(false); } try easy.perform(); const status_code = try easy.getResponseCode(); if (status_code != 200) { std.log.err("http status code: {}", .{status_code}); return error.HttpError; } var gzip = try std.compress.gzip.gzipStream(allocator, fifo.reader()); defer gzip.deinit(); try tar.instantiate(allocator, dir, gzip.reader(), skip_depth); } pub fn getTarGz( allocator: Allocator, url: [:0]const u8, dir: std.fs.Dir, xfer_ctx: ?XferCtx, ) !void { try getTarGzImpl(allocator, url, dir, 0, xfer_ctx); } pub fn getGithubRepo( allocator: Allocator, user: []const u8, repo: []const u8, ) !std.json.ValueTree { const url = try std.fmt.allocPrintZ( allocator, "https://api.github.com/repos/{s}/{s}", .{ user, repo }, ); defer allocator.free(url); var fifo = Fifo.init(allocator); defer fifo.deinit(); var headers = curl.HeaderList.init(); defer headers.freeAll(); try headers.append("Accept: application/vnd.github.v3+json"); const easy = try curl.Easy.init(); defer easy.cleanup(); try easy.setUrl(url); try easy.setHeaders(headers); try easy.setSslVerifyPeer(false); try easy.setWriteFn(curl.writeToFifo(Fifo)); try easy.setWriteData(&fifo); try easy.perform(); const status_code = try easy.getResponseCode(); if (status_code != 200) { std.log.err("http status code: {}", .{status_code}); return error.HttpError; } var parser = std.json.Parser.init(allocator, true); defer parser.deinit(); return try parser.parse(fifo.readableSlice(0)); } pub fn getGithubTopics( allocator: Allocator, user: []const u8, repo: []const u8, ) !std.json.ValueTree { const url = try std.fmt.allocPrintZ(allocator, "https://api.github.com/repos/{s}/{s}/topics", .{ user, repo }); defer allocator.free(url); var fifo = Fifo.init(allocator); defer fifo.deinit(); var headers = curl.HeaderList.init(); defer headers.freeAll(); try headers.append("Accept: application/vnd.github.mercy-preview+json"); const easy = try curl.Easy.init(); defer easy.cleanup(); try easy.setUrl(url); try easy.setHeaders(headers); try easy.setSslVerifyPeer(false); try easy.setWriteFn(curl.writeToFifo(Fifo)); try easy.setWriteData(&fifo); try easy.perform(); const status_code = try easy.getResponseCode(); if (status_code != 200) { std.log.err("http status code: {}", .{status_code}); std.log.err("{s}", .{fifo.readableSlice(0)}); return error.Explained; } var parser = std.json.Parser.init(allocator, true); defer parser.deinit(); return try parser.parse(fifo.readableSlice(0)); } pub const DeviceCodeResponse = struct { device_code: []const u8, user_code: []const u8, verification_uri: []const u8, expires_in: u64, interval: u64, }; pub fn postDeviceCode( allocator: Allocator, client_id: []const u8, scope: []const u8, ) !DeviceCodeResponse { const url = "https://github.com/login/device/code"; const payload = try std.fmt.allocPrint(allocator, "client_id={s}&scope={s}", .{ client_id, scope }); defer allocator.free(payload); var fifo = Fifo.init(allocator); defer fifo.deinit(); var headers = curl.HeaderList.init(); defer headers.freeAll(); try headers.append("Accept: application/json"); // remove expect header try headers.append("Expect:"); const easy = try curl.Easy.init(); defer easy.cleanup(); try easy.setPost(); try easy.setUrl(url); try easy.setHeaders(headers); try easy.setSslVerifyPeer(false); try easy.setPostFields(payload.ptr); try easy.setPostFieldSize(payload.len); try easy.setWriteFn(curl.writeToFifo(Fifo)); try easy.setWriteData(&fifo); try easy.perform(); const status_code = try easy.getResponseCode(); if (status_code != 200) { std.log.err("http status code: {}", .{status_code}); std.log.err("{s}", .{fifo.readableSlice(0)}); return error.Explained; } std.log.debug("message: {s}", .{fifo.readableSlice(0)}); var token_stream = std.json.TokenStream.init(fifo.readableSlice(0)); return std.json.parse(DeviceCodeResponse, &token_stream, .{ .allocator = allocator, .ignore_unknown_fields = true, }); } const PollDeviceCodeResponse = struct { access_token: []const u8, token_type: []const u8, scope: []const u8, }; pub fn pollDeviceCode( allocator: Allocator, client_id: []const u8, device_code: []const u8, ) !?[]const u8 { const url = "https://github.com/login/oauth/access_token"; const payload = try std.fmt.allocPrint( allocator, "client_id={s}&device_code={s}&grant_type=urn:ietf:params:oauth:grant-type:device_code", .{ client_id, device_code }, ); defer allocator.free(payload); var fifo = Fifo.init(allocator); defer fifo.deinit(); var headers = curl.HeaderList.init(); defer headers.freeAll(); try headers.append("Accept: application/json"); const easy = try curl.Easy.init(); defer easy.cleanup(); try easy.setPost(); try easy.setUrl(url); try easy.setHeaders(headers); try easy.setSslVerifyPeer(false); try easy.setPostFields(payload.ptr); try easy.setPostFieldSize(payload.len); try easy.setWriteFn(curl.writeToFifo(Fifo)); try easy.setWriteData(&fifo); try easy.perform(); const status_code = try easy.getResponseCode(); if (status_code != 200) { std.log.err("http status code: {}", .{status_code}); std.log.err("{s}", .{fifo.readableSlice(0)}); return error.Explained; } var parser = std.json.Parser.init(allocator, false); defer parser.deinit(); var value_tree = try parser.parse(fifo.readableSlice(0)); defer value_tree.deinit(); // TODO: error handling based on the json error codes return if (value_tree.root.Object.get("access_token")) |value| switch (value) { .String => |str| try allocator.dupe(u8, str), else => null, } else null; } pub fn postPublish( allocator: Allocator, repository_opt: ?[]const u8, access_token: []const u8, pkg: *Package, ) !void { try pkg.bundle(std.fs.cwd(), std.fs.cwd()); const filename = try pkg.filename(allocator); defer allocator.free(filename); const file = try std.fs.cwd().openFile(filename, .{}); defer { file.close(); std.fs.cwd().deleteFile(filename) catch {}; } const repository = repository_opt orelse utils.default_repo; const url = try std.fmt.allocPrintZ(allocator, "https://{s}/publish", .{repository}); defer allocator.free(url); const payload = try file.reader().readAllAlloc(allocator, std.math.maxInt(usize)); defer allocator.free(payload); var fifo = Fifo.init(allocator); defer fifo.deinit(); const authorization_header = try std.fmt.allocPrintZ(allocator, "Authorization: Bearer github {s}", .{access_token}); defer allocator.free(authorization_header); var headers = curl.HeaderList.init(); defer headers.freeAll(); try headers.append("Content-Type: application/octet-stream"); try headers.append("Accept: */*"); try headers.append(authorization_header); const easy = try curl.Easy.init(); defer easy.cleanup(); try easy.setPost(); try easy.setUrl(url); try easy.setHeaders(headers); try easy.setSslVerifyPeer(false); try easy.setPostFields(payload.ptr); try easy.setPostFieldSize(payload.len); try easy.setWriteFn(curl.writeToFifo(Fifo)); try easy.setWriteData(&fifo); try easy.perform(); const stderr = std.io.getStdErr().writer(); defer stderr.print("{s}\n", .{fifo.readableSlice(0)}) catch {}; switch (try easy.getResponseCode()) { 200 => {}, 401 => return error.Unauthorized, else => |code| { if (fifo.readableSlice(0).len > 0) { return error.Explained; } else { std.log.err("http status code: {}", .{code}); return error.HttpError; } }, } }
src/api.zig
const std = @import("std"); var gCurrentCoroutine: ?*StacklessCoroutine(void) = undefined; pub fn StacklessCoroutine(comptime T: type) type { return struct { const Self = @This(); pub const UserFunctionType = fn () callconv(.Async) void; // members allocator: *std.mem.Allocator, func: UserFunctionType, frame: ?anyframe = null, frame_buffer: []align(16) u8 = &.{}, user_data: *T, // functions pub fn init(func: UserFunctionType, user_data: *T, allocator: *std.mem.Allocator) !Self { return Self{ .allocator = allocator, .func = func, .user_data = user_data, }; } pub fn deinit(self: *Self) void { self.allocator.free(self.frame_buffer); } pub fn call(self: *Self) !void { gCurrentCoroutine = @ptrCast(@TypeOf(gCurrentCoroutine), self); if (self.frame) |frame| { resume frame; } else { self.frame_buffer = try self.allocator.allocAdvanced(u8, 16, 4096 * 4, .at_least); _ = @asyncCall(self.frame_buffer, {}, self.func, .{}); } gCurrentCoroutine = null; } pub fn yield() !void { suspend gCurrentCoroutine.?.frame = @frame(); } pub fn getUserData(self: *Self) ?*T { return self.user_data; } pub fn current() *Self { return @ptrCast(*Self, gCurrentCoroutine); } pub fn callAsync(func: anytype, args: anytype) callconv(.Async) returnType(@TypeOf(func)) { const ReturnType = returnType(@TypeOf(func)); var curr = gCurrentCoroutine orelse @panic("gCurrentCoroutine shouldn't be null."); var buff = curr.allocator.allocAdvanced(u8, 16, @frameSize(func), .at_least) catch unreachable; defer curr.allocator.free(buff); curr.frame = null; if (ReturnType != void) { var result: ReturnType = undefined; _ = @asyncCall(buff, &result, func, args); while (curr.frame) |f| { suspend curr.frame = @frame(); curr.frame = null; resume f; } return result; } else { _ = @asyncCall(buff, {}, func, args); while (curr.frame) |f| { suspend curr.frame = @frame(); curr.frame = null; resume f; } } } }; } fn returnType(comptime func: type) type { return @typeInfo(func).Fn.return_type.?; } fn frameToPointer(frame: ?anyframe) ?*i64 { if (frame) |f| { return @ptrCast(*const *i64, &f).*; } else { return null; } } fn frameCast(comptime T: type, frame: anyframe) *(anyframe->T) { return @ptrCast(*const (anyframe->T), &frame).*; }
src/stackless_coroutine.zig
const std = @import("std"); const c = @import("c.zig"); const State = struct { pass_action: c.sg_pass_action, main_pipeline: c.sg_pipeline, main_bindings: c.sg_bindings, }; var state: State = undefined; var last_time: u64 = 0; var show_test_window: bool = false; var show_another_window: bool = false; var display_menu: bool = false; var f: f32 = 0.0; var clear_color: [3]f32 = .{ 0.2, 0.2, 0.2 }; export fn init() void { var desc = std.mem.zeroes(c.sg_desc); desc.context = c.sapp_sgcontext(); c.sg_setup(&desc); c.stm_setup(); var imgui_desc = std.mem.zeroes(c.simgui_desc_t); c.simgui_setup(&imgui_desc); state.pass_action.colors[0].action = .SG_ACTION_CLEAR; state.pass_action.colors[0].value = c.sg_color{ .r = clear_color[0], .g = clear_color[1], .b = clear_color[2], .a = 1.0 }; } export fn update() void { const width = c.sapp_width(); const height = c.sapp_height(); const dt = c.stm_sec(c.stm_laptime(&last_time)); c.simgui_new_frame(width, height, dt); c.igText("Hello, world!"); _ = c.igSliderFloat("float", &f, 0.0, 1.0, "%.3f", 1.0); if (c.igColorEdit3("clear color", &clear_color[0], 0)) { state.pass_action.colors[0].value.r = clear_color[0]; state.pass_action.colors[0].value.g = clear_color[1]; state.pass_action.colors[0].value.b = clear_color[2]; } if (c.igButton("Test Window", c.ImVec2{ .x = 0.0, .y = 0.0 })) show_test_window = !show_test_window; if (c.igButton("Another Window", c.ImVec2{ .x = 0.0, .y = 0.0 })) show_another_window = !show_another_window; c.igText("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / c.igGetIO().*.Framerate, c.igGetIO().*.Framerate); if (show_another_window) { c.igSetNextWindowSize(c.ImVec2{ .x = 200, .y = 100 }, c.ImGuiCond_FirstUseEver); _ = c.igBegin("Another Window", &show_another_window, 0); c.igText("Hello"); c.igEnd(); } if (show_test_window) { c.igSetNextWindowPos(c.ImVec2{ .x = 460, .y = 20 }, c.ImGuiCond_FirstUseEver, c.ImVec2{ .x = 0, .y = 0 }); c.igShowDemoWindow(0); } c.sg_begin_default_pass(&state.pass_action, width, height); c.simgui_render(); c.sg_end_pass(); c.sg_commit(); } export fn cleanup() void { c.simgui_shutdown(); c.sg_shutdown(); } export fn event(e: [*c]const c.sapp_event) void { _ = c.simgui_handle_event(e); } pub fn main() void { var app_desc = std.mem.zeroes(c.sapp_desc); app_desc.width = 1280; app_desc.height = 720; app_desc.init_cb = init; app_desc.frame_cb = update; app_desc.cleanup_cb = cleanup; app_desc.event_cb = event; app_desc.window_title = "IMGUI (sokol-zig)"; _ = c.sapp_run(&app_desc); }
src/example_imgui.zig
const std = @import("std"); const stdout = std.io.getStdOut().writer(); const print = stdout.print; const os = std.os; const Allocator = std.mem.Allocator; const funcs = @import("funcs.zig"); pub const Escapes = struct { o: [:0]const u8 = undefined, c: [:0]const u8 = undefined, pub fn init(open: [:0]const u8, close: [:0]const u8) Escapes { return Escapes{ .o = open, .c = close }; } }; const Shell = enum { zsh, bash, unknown, }; pub const C = .{ .reset = "\x1b[00m", .bold = "\x1b[01m", .italic = "\x1b[03m", .underline = "\x1b[04m", .reverse = "\x1b[07m", .italic_off = "\x1b[23m", .underline_off = "\x1b[24m", .reverse_off = "\x1b[27m", .default = "\x1b[91m", .black = "\x1b[30m", .red = "\x1b[31m", .green = "\x1b[32m", .yellow = "\x1b[33m", .blue = "\x1b[34m", .magenta = "\x1b[35m", .cyan = "\x1b[36m", .white = "\x1b[37m", .bright_black = "\x1b[90m", .bright_red = "\x1b[91m", .bright_green = "\x1b[92m", .bright_yellow = "\x1b[99m", .bright_blue = "\x1b[94m", .bright_magenta = "\x1b[95m", .bright_cyan = "\x1b[96m", .bright_white = "\x1b[97m", }; pub var A: *Allocator = undefined; pub var E: Escapes = undefined; pub var CWD: []u8 = undefined; pub fn main() !void { // allocator setup var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); A = &arena.allocator; // get the specified shell and initialize escape codes var shell = Shell.unknown; if (std.mem.len(os.argv) > 1) { var arg = std.mem.spanZ(os.argv[1]); if (std.mem.eql(u8, arg, "zsh")) { shell = Shell.zsh; } else if ((std.mem.eql(u8, arg, "bash"))) { shell = Shell.bash; } } switch (shell) { .zsh => { E = Escapes.init("%{", "%}"); }, .bash => { E = Escapes.init("\\[", "\\]"); }, else => { E = Escapes.init("", ""); const c = @cImport(@cInclude("stdlib.h")); _ = c.unsetenv("SHELL"); // force 'interactive' for subprograms }, } // state var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; CWD = try std.os.getcwd(&buf); const long = funcs.is_env_true("PROMPT_LONG"); // print prompt try funcs.newline_if("PROMPT_LINE_BEFORE"); if (!funcs.is_env_true("PROMPT_BARE")) { try funcs.hr(); try funcs.prefix(); try funcs.script(); try funcs.tab(); try funcs.screen(); try funcs.venv(); try funcs.date(); var show_sep = false; // showing the host (and user, if not su/root) is unnecessary if local if (funcs.is_root() or funcs.is_su() or long) { show_sep = true; try funcs.user(); } if (!funcs.is_local() or long) { show_sep = true; try funcs.at(); try funcs.host(); } // if no user or host, remove sep too if (show_sep) { try funcs.sep(); } try funcs.path(); try funcs.repo(); try funcs.jobs(); try funcs.direnv(); try funcs.newline_if("PROMPT_LINE_AFTER"); } try funcs.char(); }
prompt.zig
const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; const CrossTarget = std.zig.CrossTarget; const Target = std.Target; const build_options = @import("build_options"); const stage2 = @import("main.zig"); const fatal = stage2.fatal; const Compilation = @import("Compilation.zig"); const translate_c = @import("translate_c.zig"); const target_util = @import("target.zig"); comptime { assert(std.builtin.link_libc); assert(build_options.is_stage1); assert(build_options.have_llvm); _ = @import("compiler_rt"); } pub const log = stage2.log; pub const log_level = stage2.log_level; pub export fn main(argc: c_int, argv: [*][*:0]u8) c_int { std.os.argv = argv[0..@intCast(usize, argc)]; std.debug.maybeEnableSegfaultHandler(); zig_stage1_os_init(); const gpa = std.heap.c_allocator; var arena_instance = std.heap.ArenaAllocator.init(gpa); defer arena_instance.deinit(); const arena = &arena_instance.allocator; const args = arena.alloc([]const u8, @intCast(usize, argc)) catch fatal("{}", .{"OutOfMemory"}); for (args) |*arg, i| { arg.* = mem.spanZ(argv[i]); } if (std.builtin.mode == .Debug) { stage2.mainArgs(gpa, arena, args) catch unreachable; } else { stage2.mainArgs(gpa, arena, args) catch |err| fatal("{}", .{@errorName(err)}); } return 0; } /// Matches stage2.Color; pub const ErrColor = c_int; /// Matches std.builtin.CodeModel pub const CodeModel = c_int; /// Matches std.Target.Os.Tag pub const OS = c_int; /// Matches std.builtin.BuildMode pub const BuildMode = c_int; pub const TargetSubsystem = extern enum(c_int) { Console, Windows, Posix, Native, EfiApplication, EfiBootServiceDriver, EfiRom, EfiRuntimeDriver, Auto, }; pub const Pkg = extern struct { name_ptr: [*]const u8, name_len: usize, path_ptr: [*]const u8, path_len: usize, children_ptr: [*]*Pkg, children_len: usize, parent: ?*Pkg, }; pub const Module = extern struct { root_name_ptr: [*]const u8, root_name_len: usize, emit_o_ptr: [*]const u8, emit_o_len: usize, emit_h_ptr: [*]const u8, emit_h_len: usize, emit_asm_ptr: [*]const u8, emit_asm_len: usize, emit_llvm_ir_ptr: [*]const u8, emit_llvm_ir_len: usize, emit_analysis_json_ptr: [*]const u8, emit_analysis_json_len: usize, emit_docs_ptr: [*]const u8, emit_docs_len: usize, builtin_zig_path_ptr: [*]const u8, builtin_zig_path_len: usize, test_filter_ptr: [*]const u8, test_filter_len: usize, test_name_prefix_ptr: [*]const u8, test_name_prefix_len: usize, userdata: usize, root_pkg: *Pkg, main_progress_node: ?*std.Progress.Node, code_model: CodeModel, subsystem: TargetSubsystem, err_color: ErrColor, pic: bool, pie: bool, link_libc: bool, link_libcpp: bool, strip: bool, is_single_threaded: bool, dll_export_fns: bool, link_mode_dynamic: bool, valgrind_enabled: bool, function_sections: bool, enable_stack_probing: bool, enable_time_report: bool, enable_stack_report: bool, test_is_evented: bool, verbose_tokenize: bool, verbose_ast: bool, verbose_ir: bool, verbose_llvm_ir: bool, verbose_cimport: bool, verbose_llvm_cpu_features: bool, // Set by stage1 have_c_main: bool, have_winmain: bool, have_wwinmain: bool, have_winmain_crt_startup: bool, have_wwinmain_crt_startup: bool, have_dllmain_crt_startup: bool, pub fn build_object(mod: *Module) void { zig_stage1_build_object(mod); } pub fn destroy(mod: *Module) void { zig_stage1_destroy(mod); } }; extern fn zig_stage1_os_init() void; pub const create = zig_stage1_create; extern fn zig_stage1_create( optimize_mode: BuildMode, main_pkg_path_ptr: [*]const u8, main_pkg_path_len: usize, root_src_path_ptr: [*]const u8, root_src_path_len: usize, zig_lib_dir_ptr: [*c]const u8, zig_lib_dir_len: usize, target: [*c]const Stage2Target, is_test_build: bool, ) ?*Module; extern fn zig_stage1_build_object(*Module) void; extern fn zig_stage1_destroy(*Module) void; // ABI warning export fn stage2_panic(ptr: [*]const u8, len: usize) void { @panic(ptr[0..len]); } // ABI warning const Error = extern enum { None, OutOfMemory, InvalidFormat, SemanticAnalyzeFail, AccessDenied, Interrupted, SystemResources, FileNotFound, FileSystem, FileTooBig, DivByZero, Overflow, PathAlreadyExists, Unexpected, ExactDivRemainder, NegativeDenominator, ShiftedOutOneBits, CCompileErrors, EndOfFile, IsDir, NotDir, UnsupportedOperatingSystem, SharingViolation, PipeBusy, PrimitiveTypeNotFound, CacheUnavailable, PathTooLong, CCompilerCannotFindFile, NoCCompilerInstalled, ReadingDepFile, InvalidDepFile, MissingArchitecture, MissingOperatingSystem, UnknownArchitecture, UnknownOperatingSystem, UnknownABI, InvalidFilename, DiskQuota, DiskSpace, UnexpectedWriteFailure, UnexpectedSeekFailure, UnexpectedFileTruncationFailure, Unimplemented, OperationAborted, BrokenPipe, NoSpaceLeft, NotLazy, IsAsync, ImportOutsidePkgPath, UnknownCpuModel, UnknownCpuFeature, InvalidCpuFeatures, InvalidLlvmCpuFeaturesFormat, UnknownApplicationBinaryInterface, ASTUnitFailure, BadPathName, SymLinkLoop, ProcessFdQuotaExceeded, SystemFdQuotaExceeded, NoDevice, DeviceBusy, UnableToSpawnCCompiler, CCompilerExitCode, CCompilerCrashed, CCompilerCannotFindHeaders, LibCRuntimeNotFound, LibCStdLibHeaderNotFound, LibCKernel32LibNotFound, UnsupportedArchitecture, WindowsSdkNotFound, UnknownDynamicLinkerPath, TargetHasNoDynamicLinker, InvalidAbiVersion, InvalidOperatingSystemVersion, UnknownClangOption, NestedResponseFile, ZigIsTheCCompiler, FileBusy, Locked, }; // ABI warning export fn stage2_attach_segfault_handler() void { if (std.debug.runtime_safety and std.debug.have_segfault_handling_support) { std.debug.attachSegfaultHandler(); } } // ABI warning export fn stage2_progress_create() *std.Progress { const ptr = std.heap.c_allocator.create(std.Progress) catch @panic("out of memory"); ptr.* = std.Progress{}; return ptr; } // ABI warning export fn stage2_progress_destroy(progress: *std.Progress) void { std.heap.c_allocator.destroy(progress); } // ABI warning export fn stage2_progress_start_root( progress: *std.Progress, name_ptr: [*]const u8, name_len: usize, estimated_total_items: usize, ) *std.Progress.Node { return progress.start( name_ptr[0..name_len], if (estimated_total_items == 0) null else estimated_total_items, ) catch @panic("timer unsupported"); } // ABI warning export fn stage2_progress_disable_tty(progress: *std.Progress) void { progress.terminal = null; } // ABI warning export fn stage2_progress_start( node: *std.Progress.Node, name_ptr: [*]const u8, name_len: usize, estimated_total_items: usize, ) *std.Progress.Node { const child_node = std.heap.c_allocator.create(std.Progress.Node) catch @panic("out of memory"); child_node.* = node.start( name_ptr[0..name_len], if (estimated_total_items == 0) null else estimated_total_items, ); child_node.activate(); return child_node; } // ABI warning export fn stage2_progress_end(node: *std.Progress.Node) void { node.end(); if (&node.context.root != node) { std.heap.c_allocator.destroy(node); } } // ABI warning export fn stage2_progress_complete_one(node: *std.Progress.Node) void { node.completeOne(); } // ABI warning export fn stage2_progress_update_node(node: *std.Progress.Node, done_count: usize, total_count: usize) void { node.completed_items = done_count; node.estimated_total_items = total_count; node.activate(); node.context.maybeRefresh(); } // ABI warning pub const Stage2Target = extern struct { arch: c_int, os: OS, abi: c_int, is_native_os: bool, is_native_cpu: bool, llvm_cpu_name: ?[*:0]const u8, llvm_cpu_features: ?[*:0]const u8, }; // ABI warning const Stage2SemVer = extern struct { major: u32, minor: u32, patch: u32, }; // ABI warning export fn stage2_cimport( stage1: *Module, c_src_ptr: [*]const u8, c_src_len: usize, out_zig_path_ptr: *[*]const u8, out_zig_path_len: *usize, out_errors_ptr: *[*]translate_c.ClangErrMsg, out_errors_len: *usize, ) Error { const comp = @intToPtr(*Compilation, stage1.userdata); const c_src = c_src_ptr[0..c_src_len]; const result = comp.cImport(c_src) catch |err| switch (err) { error.SystemResources => return .SystemResources, error.OperationAborted => return .OperationAborted, error.BrokenPipe => return .BrokenPipe, error.DiskQuota => return .DiskQuota, error.FileTooBig => return .FileTooBig, error.NoSpaceLeft => return .NoSpaceLeft, error.AccessDenied => return .AccessDenied, error.OutOfMemory => return .OutOfMemory, error.Unexpected => return .Unexpected, error.InputOutput => return .FileSystem, error.ASTUnitFailure => return .ASTUnitFailure, error.CacheUnavailable => return .CacheUnavailable, else => return .Unexpected, }; out_zig_path_ptr.* = result.out_zig_path.ptr; out_zig_path_len.* = result.out_zig_path.len; out_errors_ptr.* = result.errors.ptr; out_errors_len.* = result.errors.len; if (result.errors.len != 0) return .CCompileErrors; return Error.None; } export fn stage2_add_link_lib( stage1: *Module, lib_name_ptr: [*c]const u8, lib_name_len: usize, symbol_name_ptr: [*c]const u8, symbol_name_len: usize, ) ?[*:0]const u8 { const comp = @intToPtr(*Compilation, stage1.userdata); const lib_name = std.ascii.allocLowerString(comp.gpa, lib_name_ptr[0..lib_name_len]) catch return "out of memory"; const target = comp.getTarget(); const is_libc = target_util.is_libc_lib_name(target, lib_name); if (is_libc) { if (!comp.bin_file.options.link_libc) { return "dependency on libc must be explicitly specified in the build command"; } return null; } if (target_util.is_libcpp_lib_name(target, lib_name)) { if (!comp.bin_file.options.link_libcpp) { return "dependency on libc++ must be explicitly specified in the build command"; } return null; } if (!target.isWasm() and !comp.bin_file.options.pic) { return std.fmt.allocPrint0( comp.gpa, "dependency on dynamic library '{s}' requires enabling Position Independent Code. Fixed by `-l{s}` or `-fPIC`.", .{ lib_name, lib_name }, ) catch "out of memory"; } comp.stage1AddLinkLib(lib_name) catch |err| { return std.fmt.allocPrint0(comp.gpa, "unable to add link lib '{s}': {s}", .{ lib_name, @errorName(err), }) catch "out of memory"; }; return null; } export fn stage2_fetch_file( stage1: *Module, path_ptr: [*]const u8, path_len: usize, result_len: *usize, ) ?[*]const u8 { const comp = @intToPtr(*Compilation, stage1.userdata); const file_path = path_ptr[0..path_len]; const max_file_size = std.math.maxInt(u32); const contents = comp.stage1_cache_manifest.addFilePostFetch(file_path, max_file_size) catch return null; result_len.* = contents.len; // TODO https://github.com/ziglang/zig/issues/3328#issuecomment-716749475 if (contents.len == 0) return @intToPtr(?[*]const u8, 0x1); return contents.ptr; }
src/stage1.zig
const builtin = @import("builtin"); const is_test = builtin.is_test; const is_gnu = switch (builtin.abi) { .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => true, else => false, }; const is_mingw = builtin.os == .windows and is_gnu; comptime { const linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Weak; const strong_linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong; switch (builtin.arch) { .i386, .x86_64 => @export(@import("compiler_rt/stack_probe.zig").zig_probe_stack, .{ .name = "__zig_probe_stack", .linkage = linkage }), else => {}, } @export(@import("compiler_rt/comparesf2.zig").__lesf2, .{ .name = "__lesf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__ledf2, .{ .name = "__ledf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__letf2, .{ .name = "__letf2", .linkage = linkage }); @export(@import("compiler_rt/comparesf2.zig").__gesf2, .{ .name = "__gesf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__gedf2, .{ .name = "__gedf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__getf2, .{ .name = "__getf2", .linkage = linkage }); if (!is_test) { @export(@import("compiler_rt/comparesf2.zig").__lesf2, .{ .name = "__cmpsf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__ledf2, .{ .name = "__cmpdf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__letf2, .{ .name = "__cmptf2", .linkage = linkage }); @export(@import("compiler_rt/comparesf2.zig").__eqsf2, .{ .name = "__eqsf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__eqdf2, .{ .name = "__eqdf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__letf2, .{ .name = "__eqtf2", .linkage = linkage }); @export(@import("compiler_rt/comparesf2.zig").__ltsf2, .{ .name = "__ltsf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__ltdf2, .{ .name = "__ltdf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__letf2, .{ .name = "__lttf2", .linkage = linkage }); @export(@import("compiler_rt/comparesf2.zig").__nesf2, .{ .name = "__nesf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__nedf2, .{ .name = "__nedf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__letf2, .{ .name = "__netf2", .linkage = linkage }); @export(@import("compiler_rt/comparesf2.zig").__gtsf2, .{ .name = "__gtsf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__gtdf2, .{ .name = "__gtdf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__getf2, .{ .name = "__gttf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendhfsf2, .{ .name = "__gnu_h2f_ieee", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncsfhf2, .{ .name = "__gnu_f2h_ieee", .linkage = linkage }); } @export(@import("compiler_rt/comparesf2.zig").__unordsf2, .{ .name = "__unordsf2", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__unorddf2, .{ .name = "__unorddf2", .linkage = linkage }); @export(@import("compiler_rt/comparetf2.zig").__unordtf2, .{ .name = "__unordtf2", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__addsf3, .{ .name = "__addsf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__adddf3, .{ .name = "__adddf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__addtf3, .{ .name = "__addtf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__subsf3, .{ .name = "__subsf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__subdf3, .{ .name = "__subdf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__subtf3, .{ .name = "__subtf3", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__mulsf3, .{ .name = "__mulsf3", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__muldf3, .{ .name = "__muldf3", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__multf3, .{ .name = "__multf3", .linkage = linkage }); @export(@import("compiler_rt/divsf3.zig").__divsf3, .{ .name = "__divsf3", .linkage = linkage }); @export(@import("compiler_rt/divdf3.zig").__divdf3, .{ .name = "__divdf3", .linkage = linkage }); @export(@import("compiler_rt/ashlti3.zig").__ashlti3, .{ .name = "__ashlti3", .linkage = linkage }); @export(@import("compiler_rt/lshrti3.zig").__lshrti3, .{ .name = "__lshrti3", .linkage = linkage }); @export(@import("compiler_rt/ashrti3.zig").__ashrti3, .{ .name = "__ashrti3", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsidf, .{ .name = "__floatsidf", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsisf, .{ .name = "__floatsisf", .linkage = linkage }); @export(@import("compiler_rt/floatdidf.zig").__floatdidf, .{ .name = "__floatdidf", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsitf, .{ .name = "__floatsitf", .linkage = linkage }); @export(@import("compiler_rt/floatunsisf.zig").__floatunsisf, .{ .name = "__floatunsisf", .linkage = linkage }); @export(@import("compiler_rt/floatundisf.zig").__floatundisf, .{ .name = "__floatundisf", .linkage = linkage }); @export(@import("compiler_rt/floatunsidf.zig").__floatunsidf, .{ .name = "__floatunsidf", .linkage = linkage }); @export(@import("compiler_rt/floatundidf.zig").__floatundidf, .{ .name = "__floatundidf", .linkage = linkage }); @export(@import("compiler_rt/floattitf.zig").__floattitf, .{ .name = "__floattitf", .linkage = linkage }); @export(@import("compiler_rt/floattidf.zig").__floattidf, .{ .name = "__floattidf", .linkage = linkage }); @export(@import("compiler_rt/floattisf.zig").__floattisf, .{ .name = "__floattisf", .linkage = linkage }); @export(@import("compiler_rt/floatunditf.zig").__floatunditf, .{ .name = "__floatunditf", .linkage = linkage }); @export(@import("compiler_rt/floatunsitf.zig").__floatunsitf, .{ .name = "__floatunsitf", .linkage = linkage }); @export(@import("compiler_rt/floatuntitf.zig").__floatuntitf, .{ .name = "__floatuntitf", .linkage = linkage }); @export(@import("compiler_rt/floatuntidf.zig").__floatuntidf, .{ .name = "__floatuntidf", .linkage = linkage }); @export(@import("compiler_rt/floatuntisf.zig").__floatuntisf, .{ .name = "__floatuntisf", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extenddftf2, .{ .name = "__extenddftf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendsftf2, .{ .name = "__extendsftf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendhfsf2, .{ .name = "__extendhfsf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncsfhf2, .{ .name = "__truncsfhf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncdfhf2, .{ .name = "__truncdfhf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__trunctfdf2, .{ .name = "__trunctfdf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__trunctfsf2, .{ .name = "__trunctfsf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncdfsf2, .{ .name = "__truncdfsf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendsfdf2, .{ .name = "__extendsfdf2", .linkage = linkage }); @export(@import("compiler_rt/fixunssfsi.zig").__fixunssfsi, .{ .name = "__fixunssfsi", .linkage = linkage }); @export(@import("compiler_rt/fixunssfdi.zig").__fixunssfdi, .{ .name = "__fixunssfdi", .linkage = linkage }); @export(@import("compiler_rt/fixunssfti.zig").__fixunssfti, .{ .name = "__fixunssfti", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfsi.zig").__fixunsdfsi, .{ .name = "__fixunsdfsi", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfdi.zig").__fixunsdfdi, .{ .name = "__fixunsdfdi", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfti.zig").__fixunsdfti, .{ .name = "__fixunsdfti", .linkage = linkage }); @export(@import("compiler_rt/fixunstfsi.zig").__fixunstfsi, .{ .name = "__fixunstfsi", .linkage = linkage }); @export(@import("compiler_rt/fixunstfdi.zig").__fixunstfdi, .{ .name = "__fixunstfdi", .linkage = linkage }); @export(@import("compiler_rt/fixunstfti.zig").__fixunstfti, .{ .name = "__fixunstfti", .linkage = linkage }); @export(@import("compiler_rt/fixdfdi.zig").__fixdfdi, .{ .name = "__fixdfdi", .linkage = linkage }); @export(@import("compiler_rt/fixdfsi.zig").__fixdfsi, .{ .name = "__fixdfsi", .linkage = linkage }); @export(@import("compiler_rt/fixdfti.zig").__fixdfti, .{ .name = "__fixdfti", .linkage = linkage }); @export(@import("compiler_rt/fixsfdi.zig").__fixsfdi, .{ .name = "__fixsfdi", .linkage = linkage }); @export(@import("compiler_rt/fixsfsi.zig").__fixsfsi, .{ .name = "__fixsfsi", .linkage = linkage }); @export(@import("compiler_rt/fixsfti.zig").__fixsfti, .{ .name = "__fixsfti", .linkage = linkage }); @export(@import("compiler_rt/fixtfdi.zig").__fixtfdi, .{ .name = "__fixtfdi", .linkage = linkage }); @export(@import("compiler_rt/fixtfsi.zig").__fixtfsi, .{ .name = "__fixtfsi", .linkage = linkage }); @export(@import("compiler_rt/fixtfti.zig").__fixtfti, .{ .name = "__fixtfti", .linkage = linkage }); @export(@import("compiler_rt/udivmoddi4.zig").__udivmoddi4, .{ .name = "__udivmoddi4", .linkage = linkage }); @export(@import("compiler_rt/popcountdi2.zig").__popcountdi2, .{ .name = "__popcountdi2", .linkage = linkage }); @export(@import("compiler_rt/muldi3.zig").__muldi3, .{ .name = "__muldi3", .linkage = linkage }); @export(__divmoddi4, .{ .name = "__divmoddi4", .linkage = linkage }); @export(__divsi3, .{ .name = "__divsi3", .linkage = linkage }); @export(__divdi3, .{ .name = "__divdi3", .linkage = linkage }); @export(__udivsi3, .{ .name = "__udivsi3", .linkage = linkage }); @export(__udivdi3, .{ .name = "__udivdi3", .linkage = linkage }); @export(__modsi3, .{ .name = "__modsi3", .linkage = linkage }); @export(__moddi3, .{ .name = "__moddi3", .linkage = linkage }); @export(__umodsi3, .{ .name = "__umodsi3", .linkage = linkage }); @export(__umoddi3, .{ .name = "__umoddi3", .linkage = linkage }); @export(__divmodsi4, .{ .name = "__divmodsi4", .linkage = linkage }); @export(__udivmodsi4, .{ .name = "__udivmodsi4", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__negsf2, .{ .name = "__negsf2", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__negdf2, .{ .name = "__negdf2", .linkage = linkage }); if (is_arm_arch and !is_arm_64 and !is_test) { @export(__aeabi_unwind_cpp_pr0, .{ .name = "__aeabi_unwind_cpp_pr0", .linkage = strong_linkage }); @export(__aeabi_unwind_cpp_pr1, .{ .name = "__aeabi_unwind_cpp_pr1", .linkage = linkage }); @export(__aeabi_unwind_cpp_pr2, .{ .name = "__aeabi_unwind_cpp_pr2", .linkage = linkage }); @export(@import("compiler_rt/muldi3.zig").__muldi3, .{ .name = "__aeabi_lmul", .linkage = linkage }); @export(__aeabi_ldivmod, .{ .name = "__aeabi_ldivmod", .linkage = linkage }); @export(__aeabi_uldivmod, .{ .name = "__aeabi_uldivmod", .linkage = linkage }); @export(__divsi3, .{ .name = "__aeabi_idiv", .linkage = linkage }); @export(__aeabi_idivmod, .{ .name = "__aeabi_idivmod", .linkage = linkage }); @export(__udivsi3, .{ .name = "__aeabi_uidiv", .linkage = linkage }); @export(__aeabi_uidivmod, .{ .name = "__aeabi_uidivmod", .linkage = linkage }); @export(__aeabi_memcpy, .{ .name = "__aeabi_memcpy", .linkage = linkage }); @export(__aeabi_memcpy, .{ .name = "__aeabi_memcpy4", .linkage = linkage }); @export(__aeabi_memcpy, .{ .name = "__aeabi_memcpy8", .linkage = linkage }); @export(__aeabi_memmove, .{ .name = "__aeabi_memmove", .linkage = linkage }); @export(__aeabi_memmove, .{ .name = "__aeabi_memmove4", .linkage = linkage }); @export(__aeabi_memmove, .{ .name = "__aeabi_memmove8", .linkage = linkage }); @export(__aeabi_memset, .{ .name = "__aeabi_memset", .linkage = linkage }); @export(__aeabi_memset, .{ .name = "__aeabi_memset4", .linkage = linkage }); @export(__aeabi_memset, .{ .name = "__aeabi_memset8", .linkage = linkage }); @export(__aeabi_memclr, .{ .name = "__aeabi_memclr", .linkage = linkage }); @export(__aeabi_memclr, .{ .name = "__aeabi_memclr4", .linkage = linkage }); @export(__aeabi_memclr, .{ .name = "__aeabi_memclr8", .linkage = linkage }); @export(__aeabi_memcmp, .{ .name = "__aeabi_memcmp", .linkage = linkage }); @export(__aeabi_memcmp, .{ .name = "__aeabi_memcmp4", .linkage = linkage }); @export(__aeabi_memcmp, .{ .name = "__aeabi_memcmp8", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__aeabi_f2d, .{ .name = "__aeabi_f2d", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__aeabi_i2d, .{ .name = "__aeabi_i2d", .linkage = linkage }); @export(@import("compiler_rt/floatdidf.zig").__aeabi_l2d, .{ .name = "__aeabi_l2d", .linkage = linkage }); @export(@import("compiler_rt/floatunsidf.zig").__aeabi_ui2d, .{ .name = "__aeabi_ui2d", .linkage = linkage }); @export(@import("compiler_rt/floatundidf.zig").__aeabi_ul2d, .{ .name = "__aeabi_ul2d", .linkage = linkage }); @export(@import("compiler_rt/floatunsisf.zig").__aeabi_ui2f, .{ .name = "__aeabi_ui2f", .linkage = linkage }); @export(@import("compiler_rt/floatundisf.zig").__aeabi_ul2f, .{ .name = "__aeabi_ul2f", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__aeabi_fneg, .{ .name = "__aeabi_fneg", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__aeabi_dneg, .{ .name = "__aeabi_dneg", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__aeabi_fmul, .{ .name = "__aeabi_fmul", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__aeabi_dmul, .{ .name = "__aeabi_dmul", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__aeabi_d2h, .{ .name = "__aeabi_d2h", .linkage = linkage }); @export(@import("compiler_rt/fixunssfdi.zig").__aeabi_f2ulz, .{ .name = "__aeabi_f2ulz", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfdi.zig").__aeabi_d2ulz, .{ .name = "__aeabi_d2ulz", .linkage = linkage }); @export(@import("compiler_rt/fixsfdi.zig").__aeabi_f2lz, .{ .name = "__aeabi_f2lz", .linkage = linkage }); @export(@import("compiler_rt/fixdfdi.zig").__aeabi_d2lz, .{ .name = "__aeabi_d2lz", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfsi.zig").__aeabi_d2uiz, .{ .name = "__aeabi_d2uiz", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__aeabi_h2f, .{ .name = "__aeabi_h2f", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__aeabi_f2h, .{ .name = "__aeabi_f2h", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__aeabi_i2f, .{ .name = "__aeabi_i2f", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__aeabi_d2f, .{ .name = "__aeabi_d2f", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_fadd, .{ .name = "__aeabi_fadd", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_dadd, .{ .name = "__aeabi_dadd", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_fsub, .{ .name = "__aeabi_fsub", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_dsub, .{ .name = "__aeabi_dsub", .linkage = linkage }); @export(@import("compiler_rt/fixunssfsi.zig").__aeabi_f2uiz, .{ .name = "__aeabi_f2uiz", .linkage = linkage }); @export(@import("compiler_rt/fixsfsi.zig").__aeabi_f2iz, .{ .name = "__aeabi_f2iz", .linkage = linkage }); @export(@import("compiler_rt/fixdfsi.zig").__aeabi_d2iz, .{ .name = "__aeabi_d2iz", .linkage = linkage }); @export(@import("compiler_rt/divsf3.zig").__aeabi_fdiv, .{ .name = "__aeabi_fdiv", .linkage = linkage }); @export(@import("compiler_rt/divdf3.zig").__aeabi_ddiv, .{ .name = "__aeabi_ddiv", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_fcmp.zig").__aeabi_fcmpeq, .{ .name = "__aeabi_fcmpeq", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_fcmp.zig").__aeabi_fcmplt, .{ .name = "__aeabi_fcmplt", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_fcmp.zig").__aeabi_fcmple, .{ .name = "__aeabi_fcmple", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_fcmp.zig").__aeabi_fcmpge, .{ .name = "__aeabi_fcmpge", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_fcmp.zig").__aeabi_fcmpgt, .{ .name = "__aeabi_fcmpgt", .linkage = linkage }); @export(@import("compiler_rt/comparesf2.zig").__aeabi_fcmpun, .{ .name = "__aeabi_fcmpun", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_dcmp.zig").__aeabi_dcmpeq, .{ .name = "__aeabi_dcmpeq", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_dcmp.zig").__aeabi_dcmplt, .{ .name = "__aeabi_dcmplt", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_dcmp.zig").__aeabi_dcmple, .{ .name = "__aeabi_dcmple", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_dcmp.zig").__aeabi_dcmpge, .{ .name = "__aeabi_dcmpge", .linkage = linkage }); @export(@import("compiler_rt/arm/aeabi_dcmp.zig").__aeabi_dcmpgt, .{ .name = "__aeabi_dcmpgt", .linkage = linkage }); @export(@import("compiler_rt/comparedf2.zig").__aeabi_dcmpun, .{ .name = "__aeabi_dcmpun", .linkage = linkage }); } if (builtin.os == .windows) { // Default stack-probe functions emitted by LLVM if (is_mingw) { @export(@import("compiler_rt/stack_probe.zig")._chkstk, .{ .name = "_alloca", .linkage = strong_linkage }); @export(@import("compiler_rt/stack_probe.zig").___chkstk_ms, .{ .name = "___chkstk_ms", .linkage = strong_linkage }); } else if (!builtin.link_libc) { // This symbols are otherwise exported by MSVCRT.lib @export(@import("compiler_rt/stack_probe.zig")._chkstk, .{ .name = "_chkstk", .linkage = strong_linkage }); @export(@import("compiler_rt/stack_probe.zig").__chkstk, .{ .name = "__chkstk", .linkage = strong_linkage }); } if (is_mingw) { @export(__stack_chk_fail, .{ .name = "__stack_chk_fail", .linkage = strong_linkage }); @export(__stack_chk_guard, .{ .name = "__stack_chk_guard", .linkage = strong_linkage }); } switch (builtin.arch) { .i386 => { // Don't let LLVM apply the stdcall name mangling on those MSVC // builtin functions @export(@import("compiler_rt/aulldiv.zig")._alldiv, .{ .name = "\x01__alldiv", .linkage = strong_linkage }); @export(@import("compiler_rt/aulldiv.zig")._aulldiv, .{ .name = "\x01__aulldiv", .linkage = strong_linkage }); @export(@import("compiler_rt/aullrem.zig")._allrem, .{ .name = "\x01__allrem", .linkage = strong_linkage }); @export(@import("compiler_rt/aullrem.zig")._aullrem, .{ .name = "\x01__aullrem", .linkage = strong_linkage }); @export(@import("compiler_rt/divti3.zig").__divti3, .{ .name = "__divti3", .linkage = linkage }); @export(@import("compiler_rt/modti3.zig").__modti3, .{ .name = "__modti3", .linkage = linkage }); @export(@import("compiler_rt/multi3.zig").__multi3, .{ .name = "__multi3", .linkage = linkage }); @export(@import("compiler_rt/udivti3.zig").__udivti3, .{ .name = "__udivti3", .linkage = linkage }); @export(@import("compiler_rt/udivmodti4.zig").__udivmodti4, .{ .name = "__udivmodti4", .linkage = linkage }); @export(@import("compiler_rt/umodti3.zig").__umodti3, .{ .name = "__umodti3", .linkage = linkage }); }, .x86_64 => { // The "ti" functions must use @Vector(2, u64) parameter types to adhere to the ABI // that LLVM expects compiler-rt to have. @export(@import("compiler_rt/divti3.zig").__divti3_windows_x86_64, .{ .name = "__divti3", .linkage = linkage }); @export(@import("compiler_rt/modti3.zig").__modti3_windows_x86_64, .{ .name = "__modti3", .linkage = linkage }); @export(@import("compiler_rt/multi3.zig").__multi3_windows_x86_64, .{ .name = "__multi3", .linkage = linkage }); @export(@import("compiler_rt/udivti3.zig").__udivti3_windows_x86_64, .{ .name = "__udivti3", .linkage = linkage }); @export(@import("compiler_rt/udivmodti4.zig").__udivmodti4_windows_x86_64, .{ .name = "__udivmodti4", .linkage = linkage }); @export(@import("compiler_rt/umodti3.zig").__umodti3_windows_x86_64, .{ .name = "__umodti3", .linkage = linkage }); }, else => {}, } } else { if (builtin.glibc_version != null) { @export(__stack_chk_guard, .{ .name = "__stack_chk_guard", .linkage = linkage }); } @export(@import("compiler_rt/divti3.zig").__divti3, .{ .name = "__divti3", .linkage = linkage }); @export(@import("compiler_rt/modti3.zig").__modti3, .{ .name = "__modti3", .linkage = linkage }); @export(@import("compiler_rt/multi3.zig").__multi3, .{ .name = "__multi3", .linkage = linkage }); @export(@import("compiler_rt/udivti3.zig").__udivti3, .{ .name = "__udivti3", .linkage = linkage }); @export(@import("compiler_rt/udivmodti4.zig").__udivmodti4, .{ .name = "__udivmodti4", .linkage = linkage }); @export(@import("compiler_rt/umodti3.zig").__umodti3, .{ .name = "__umodti3", .linkage = linkage }); } @export(@import("compiler_rt/muloti4.zig").__muloti4, .{ .name = "__muloti4", .linkage = linkage }); @export(@import("compiler_rt/mulodi4.zig").__mulodi4, .{ .name = "__mulodi4", .linkage = linkage }); } const std = @import("std"); const assert = std.debug.assert; const testing = std.testing; const __udivmoddi4 = @import("compiler_rt/udivmoddi4.zig").__udivmoddi4; // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { @setCold(true); if (is_test) { std.debug.panic("{}", .{msg}); } else { unreachable; } } fn __stack_chk_fail() callconv(.C) noreturn { @panic("stack smashing detected"); } extern var __stack_chk_guard: usize = blk: { var buf = [1]u8{0} ** @sizeOf(usize); buf[@sizeOf(usize) - 1] = 255; buf[@sizeOf(usize) - 2] = '\n'; break :blk @bitCast(usize, buf); }; fn __aeabi_unwind_cpp_pr0() callconv(.C) void { unreachable; } fn __aeabi_unwind_cpp_pr1() callconv(.C) void { unreachable; } fn __aeabi_unwind_cpp_pr2() callconv(.C) void { unreachable; } fn __divmoddi4(a: i64, b: i64, rem: *i64) callconv(.C) i64 { @setRuntimeSafety(is_test); const d = __divdi3(a, b); rem.* = a -% (d *% b); return d; } fn __divdi3(a: i64, b: i64) callconv(.C) i64 { @setRuntimeSafety(is_test); // Set aside the sign of the quotient. const sign = @bitCast(u64, (a ^ b) >> 63); // Take absolute value of a and b via abs(x) = (x^(x >> 63)) - (x >> 63). const abs_a = (a ^ (a >> 63)) -% (a >> 63); const abs_b = (b ^ (b >> 63)) -% (b >> 63); // Unsigned division const res = __udivmoddi4(@bitCast(u64, abs_a), @bitCast(u64, abs_b), null); // Apply sign of quotient to result and return. return @bitCast(i64, (res ^ sign) -% sign); } fn __moddi3(a: i64, b: i64) callconv(.C) i64 { @setRuntimeSafety(is_test); // Take absolute value of a and b via abs(x) = (x^(x >> 63)) - (x >> 63). const abs_a = (a ^ (a >> 63)) -% (a >> 63); const abs_b = (b ^ (b >> 63)) -% (b >> 63); // Unsigned division var r: u64 = undefined; _ = __udivmoddi4(@bitCast(u64, abs_a), @bitCast(u64, abs_b), &r); // Apply the sign of the dividend and return. return (@bitCast(i64, r) ^ (a >> 63)) -% (a >> 63); } fn __udivdi3(a: u64, b: u64) callconv(.C) u64 { @setRuntimeSafety(is_test); return __udivmoddi4(a, b, null); } fn __umoddi3(a: u64, b: u64) callconv(.C) u64 { @setRuntimeSafety(is_test); var r: u64 = undefined; _ = __udivmoddi4(a, b, &r); return r; } fn __aeabi_uidivmod(n: u32, d: u32) callconv(.C) extern struct { q: u32, r: u32, } { @setRuntimeSafety(is_test); var result: @TypeOf(__aeabi_uidivmod).ReturnType = undefined; result.q = __udivmodsi4(n, d, &result.r); return result; } fn __aeabi_uldivmod(n: u64, d: u64) callconv(.C) extern struct { q: u64, r: u64, } { @setRuntimeSafety(is_test); var result: @TypeOf(__aeabi_uldivmod).ReturnType = undefined; result.q = __udivmoddi4(n, d, &result.r); return result; } fn __aeabi_idivmod(n: i32, d: i32) callconv(.C) extern struct { q: i32, r: i32, } { @setRuntimeSafety(is_test); var result: @TypeOf(__aeabi_idivmod).ReturnType = undefined; result.q = __divmodsi4(n, d, &result.r); return result; } fn __aeabi_ldivmod(n: i64, d: i64) callconv(.C) extern struct { q: i64, r: i64, } { @setRuntimeSafety(is_test); var result: @TypeOf(__aeabi_ldivmod).ReturnType = undefined; result.q = __divmoddi4(n, d, &result.r); return result; } const is_arm_64 = switch (builtin.arch) { builtin.Arch.aarch64, builtin.Arch.aarch64_be, => true, else => false, }; const is_arm_arch = switch (builtin.arch) { builtin.Arch.arm, builtin.Arch.armeb, builtin.Arch.aarch64, builtin.Arch.aarch64_be, builtin.Arch.thumb, builtin.Arch.thumbeb, => true, else => false, }; const is_arm_32 = is_arm_arch and !is_arm_64; const use_thumb_1 = usesThumb1(builtin.arch); fn usesThumb1(arch: builtin.Arch) bool { return switch (arch) { .arm => |sub_arch| switch (sub_arch) { .v6m => true, else => false, }, .armeb => |sub_arch| switch (sub_arch) { .v6m => true, else => false, }, .thumb => |sub_arch| switch (sub_arch) { .v5, .v5te, .v4t, .v6, .v6m, .v6k, => true, else => false, }, .thumbeb => |sub_arch| switch (sub_arch) { .v5, .v5te, .v4t, .v6, .v6m, .v6k, => true, else => false, }, else => false, }; } test "usesThumb1" { testing.expect(usesThumb1(builtin.Arch{ .arm = .v6m })); testing.expect(!usesThumb1(builtin.Arch{ .arm = .v5 })); //etc. testing.expect(usesThumb1(builtin.Arch{ .armeb = .v6m })); testing.expect(!usesThumb1(builtin.Arch{ .armeb = .v5 })); //etc. testing.expect(usesThumb1(builtin.Arch{ .thumb = .v5 })); testing.expect(usesThumb1(builtin.Arch{ .thumb = .v5te })); testing.expect(usesThumb1(builtin.Arch{ .thumb = .v4t })); testing.expect(usesThumb1(builtin.Arch{ .thumb = .v6 })); testing.expect(usesThumb1(builtin.Arch{ .thumb = .v6k })); testing.expect(usesThumb1(builtin.Arch{ .thumb = .v6m })); testing.expect(!usesThumb1(builtin.Arch{ .thumb = .v6t2 })); //etc. testing.expect(usesThumb1(builtin.Arch{ .thumbeb = .v5 })); testing.expect(usesThumb1(builtin.Arch{ .thumbeb = .v5te })); testing.expect(usesThumb1(builtin.Arch{ .thumbeb = .v4t })); testing.expect(usesThumb1(builtin.Arch{ .thumbeb = .v6 })); testing.expect(usesThumb1(builtin.Arch{ .thumbeb = .v6k })); testing.expect(usesThumb1(builtin.Arch{ .thumbeb = .v6m })); testing.expect(!usesThumb1(builtin.Arch{ .thumbeb = .v6t2 })); //etc. testing.expect(!usesThumb1(builtin.Arch{ .aarch64 = .v8 })); testing.expect(!usesThumb1(builtin.Arch{ .aarch64_be = .v8 })); testing.expect(!usesThumb1(builtin.Arch.x86_64)); testing.expect(!usesThumb1(builtin.Arch.riscv32)); //etc. } const use_thumb_1_pre_armv6 = usesThumb1PreArmv6(builtin.arch); fn usesThumb1PreArmv6(arch: builtin.Arch) bool { return switch (arch) { .thumb => |sub_arch| switch (sub_arch) { .v5, .v5te, .v4t => true, else => false, }, .thumbeb => |sub_arch| switch (sub_arch) { .v5, .v5te, .v4t => true, else => false, }, else => false, }; } fn __aeabi_memcpy() callconv(.Naked) noreturn { @setRuntimeSafety(false); if (use_thumb_1) { asm volatile ( \\ push {r7, lr} \\ bl memcpy \\ pop {r7, pc} ); } else { asm volatile ( \\ b memcpy ); } unreachable; } fn __aeabi_memmove() callconv(.Naked) noreturn { @setRuntimeSafety(false); if (use_thumb_1) { asm volatile ( \\ push {r7, lr} \\ bl memmove \\ pop {r7, pc} ); } else { asm volatile ( \\ b memmove ); } unreachable; } fn __aeabi_memset() callconv(.Naked) noreturn { @setRuntimeSafety(false); if (use_thumb_1_pre_armv6) { asm volatile ( \\ eors r1, r2 \\ eors r2, r1 \\ eors r1, r2 \\ push {r7, lr} \\ b memset \\ pop {r7, pc} ); } else if (use_thumb_1) { asm volatile ( \\ mov r3, r1 \\ mov r1, r2 \\ mov r2, r3 \\ push {r7, lr} \\ b memset \\ pop {r7, pc} ); } else { asm volatile ( \\ mov r3, r1 \\ mov r1, r2 \\ mov r2, r3 \\ b memset ); } unreachable; } fn __aeabi_memclr() callconv(.Naked) noreturn { @setRuntimeSafety(false); if (use_thumb_1_pre_armv6) { asm volatile ( \\ adds r2, r1, #0 \\ movs r1, #0 \\ push {r7, lr} \\ bl memset \\ pop {r7, pc} ); } else if (use_thumb_1) { asm volatile ( \\ mov r2, r1 \\ movs r1, #0 \\ push {r7, lr} \\ bl memset \\ pop {r7, pc} ); } else { asm volatile ( \\ mov r2, r1 \\ movs r1, #0 \\ b memset ); } unreachable; } fn __aeabi_memcmp() callconv(.Naked) noreturn { @setRuntimeSafety(false); if (use_thumb_1) { asm volatile ( \\ push {r7, lr} \\ bl memcmp \\ pop {r7, pc} ); } else { asm volatile ( \\ b memcmp ); } unreachable; } fn __divmodsi4(a: i32, b: i32, rem: *i32) callconv(.C) i32 { @setRuntimeSafety(is_test); const d = __divsi3(a, b); rem.* = a -% (d * b); return d; } fn __udivmodsi4(a: u32, b: u32, rem: *u32) callconv(.C) u32 { @setRuntimeSafety(is_test); const d = __udivsi3(a, b); rem.* = @bitCast(u32, @bitCast(i32, a) -% (@bitCast(i32, d) * @bitCast(i32, b))); return d; } fn __divsi3(n: i32, d: i32) callconv(.C) i32 { @setRuntimeSafety(is_test); // Set aside the sign of the quotient. const sign = @bitCast(u32, (n ^ d) >> 31); // Take absolute value of a and b via abs(x) = (x^(x >> 31)) - (x >> 31). const abs_n = (n ^ (n >> 31)) -% (n >> 31); const abs_d = (d ^ (d >> 31)) -% (d >> 31); // abs(a) / abs(b) const res = @bitCast(u32, abs_n) / @bitCast(u32, abs_d); // Apply sign of quotient to result and return. return @bitCast(i32, (res ^ sign) -% sign); } fn __udivsi3(n: u32, d: u32) callconv(.C) u32 { @setRuntimeSafety(is_test); const n_uword_bits: c_uint = u32.bit_count; // special cases if (d == 0) return 0; // ?! if (n == 0) return 0; var sr = @bitCast(c_uint, @as(c_int, @clz(u32, d)) - @as(c_int, @clz(u32, n))); // 0 <= sr <= n_uword_bits - 1 or sr large if (sr > n_uword_bits - 1) { // d > r return 0; } if (sr == n_uword_bits - 1) { // d == 1 return n; } sr += 1; // 1 <= sr <= n_uword_bits - 1 // Not a special case var q: u32 = n << @intCast(u5, n_uword_bits - sr); var r: u32 = n >> @intCast(u5, sr); var carry: u32 = 0; while (sr > 0) : (sr -= 1) { // r:q = ((r:q) << 1) | carry r = (r << 1) | (q >> @intCast(u5, n_uword_bits - 1)); q = (q << 1) | carry; // carry = 0; // if (r.all >= d.all) // { // r.all -= d.all; // carry = 1; // } const s = @intCast(i32, d -% r -% 1) >> @intCast(u5, n_uword_bits - 1); carry = @intCast(u32, s & 1); r -= d & @bitCast(u32, s); } q = (q << 1) | carry; return q; } fn __modsi3(n: i32, d: i32) callconv(.C) i32 { @setRuntimeSafety(is_test); return n -% __divsi3(n, d) *% d; } fn __umodsi3(n: u32, d: u32) callconv(.C) u32 { @setRuntimeSafety(is_test); return n -% __udivsi3(n, d) *% d; } test "test_umoddi3" { test_one_umoddi3(0, 1, 0); test_one_umoddi3(2, 1, 0); test_one_umoddi3(0x8000000000000000, 1, 0x0); test_one_umoddi3(0x8000000000000000, 2, 0x0); test_one_umoddi3(0xFFFFFFFFFFFFFFFF, 2, 0x1); } fn test_one_umoddi3(a: u64, b: u64, expected_r: u64) void { const r = __umoddi3(a, b); testing.expect(r == expected_r); } test "test_udivsi3" { const cases = [_][3]u32{ [_]u32{ 0x00000000, 0x00000001, 0x00000000, }, [_]u32{ 0x00000000, 0x00000002, 0x00000000, }, [_]u32{ 0x00000000, 0x00000003, 0x00000000, }, [_]u32{ 0x00000000, 0x00000010, 0x00000000, }, [_]u32{ 0x00000000, 0x078644FA, 0x00000000, }, [_]u32{ 0x00000000, 0x0747AE14, 0x00000000, }, [_]u32{ 0x00000000, 0x7FFFFFFF, 0x00000000, }, [_]u32{ 0x00000000, 0x80000000, 0x00000000, }, [_]u32{ 0x00000000, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x00000000, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x00000000, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x00000001, 0x00000001, 0x00000001, }, [_]u32{ 0x00000001, 0x00000002, 0x00000000, }, [_]u32{ 0x00000001, 0x00000003, 0x00000000, }, [_]u32{ 0x00000001, 0x00000010, 0x00000000, }, [_]u32{ 0x00000001, 0x078644FA, 0x00000000, }, [_]u32{ 0x00000001, 0x0747AE14, 0x00000000, }, [_]u32{ 0x00000001, 0x7FFFFFFF, 0x00000000, }, [_]u32{ 0x00000001, 0x80000000, 0x00000000, }, [_]u32{ 0x00000001, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x00000001, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x00000001, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x00000002, 0x00000001, 0x00000002, }, [_]u32{ 0x00000002, 0x00000002, 0x00000001, }, [_]u32{ 0x00000002, 0x00000003, 0x00000000, }, [_]u32{ 0x00000002, 0x00000010, 0x00000000, }, [_]u32{ 0x00000002, 0x078644FA, 0x00000000, }, [_]u32{ 0x00000002, 0x0747AE14, 0x00000000, }, [_]u32{ 0x00000002, 0x7FFFFFFF, 0x00000000, }, [_]u32{ 0x00000002, 0x80000000, 0x00000000, }, [_]u32{ 0x00000002, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x00000002, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x00000002, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x00000003, 0x00000001, 0x00000003, }, [_]u32{ 0x00000003, 0x00000002, 0x00000001, }, [_]u32{ 0x00000003, 0x00000003, 0x00000001, }, [_]u32{ 0x00000003, 0x00000010, 0x00000000, }, [_]u32{ 0x00000003, 0x078644FA, 0x00000000, }, [_]u32{ 0x00000003, 0x0747AE14, 0x00000000, }, [_]u32{ 0x00000003, 0x7FFFFFFF, 0x00000000, }, [_]u32{ 0x00000003, 0x80000000, 0x00000000, }, [_]u32{ 0x00000003, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x00000003, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x00000003, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x00000010, 0x00000001, 0x00000010, }, [_]u32{ 0x00000010, 0x00000002, 0x00000008, }, [_]u32{ 0x00000010, 0x00000003, 0x00000005, }, [_]u32{ 0x00000010, 0x00000010, 0x00000001, }, [_]u32{ 0x00000010, 0x078644FA, 0x00000000, }, [_]u32{ 0x00000010, 0x0747AE14, 0x00000000, }, [_]u32{ 0x00000010, 0x7FFFFFFF, 0x00000000, }, [_]u32{ 0x00000010, 0x80000000, 0x00000000, }, [_]u32{ 0x00000010, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x00000010, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x00000010, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x078644FA, 0x00000001, 0x078644FA, }, [_]u32{ 0x078644FA, 0x00000002, 0x03C3227D, }, [_]u32{ 0x078644FA, 0x00000003, 0x028216FE, }, [_]u32{ 0x078644FA, 0x00000010, 0x0078644F, }, [_]u32{ 0x078644FA, 0x078644FA, 0x00000001, }, [_]u32{ 0x078644FA, 0x0747AE14, 0x00000001, }, [_]u32{ 0x078644FA, 0x7FFFFFFF, 0x00000000, }, [_]u32{ 0x078644FA, 0x80000000, 0x00000000, }, [_]u32{ 0x078644FA, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x078644FA, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x078644FA, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x0747AE14, 0x00000001, 0x0747AE14, }, [_]u32{ 0x0747AE14, 0x00000002, 0x03A3D70A, }, [_]u32{ 0x0747AE14, 0x00000003, 0x026D3A06, }, [_]u32{ 0x0747AE14, 0x00000010, 0x00747AE1, }, [_]u32{ 0x0747AE14, 0x078644FA, 0x00000000, }, [_]u32{ 0x0747AE14, 0x0747AE14, 0x00000001, }, [_]u32{ 0x0747AE14, 0x7FFFFFFF, 0x00000000, }, [_]u32{ 0x0747AE14, 0x80000000, 0x00000000, }, [_]u32{ 0x0747AE14, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x0747AE14, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x0747AE14, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x7FFFFFFF, 0x00000001, 0x7FFFFFFF, }, [_]u32{ 0x7FFFFFFF, 0x00000002, 0x3FFFFFFF, }, [_]u32{ 0x7FFFFFFF, 0x00000003, 0x2AAAAAAA, }, [_]u32{ 0x7FFFFFFF, 0x00000010, 0x07FFFFFF, }, [_]u32{ 0x7FFFFFFF, 0x078644FA, 0x00000011, }, [_]u32{ 0x7FFFFFFF, 0x0747AE14, 0x00000011, }, [_]u32{ 0x7FFFFFFF, 0x7FFFFFFF, 0x00000001, }, [_]u32{ 0x7FFFFFFF, 0x80000000, 0x00000000, }, [_]u32{ 0x7FFFFFFF, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x7FFFFFFF, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x7FFFFFFF, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0x80000000, 0x00000001, 0x80000000, }, [_]u32{ 0x80000000, 0x00000002, 0x40000000, }, [_]u32{ 0x80000000, 0x00000003, 0x2AAAAAAA, }, [_]u32{ 0x80000000, 0x00000010, 0x08000000, }, [_]u32{ 0x80000000, 0x078644FA, 0x00000011, }, [_]u32{ 0x80000000, 0x0747AE14, 0x00000011, }, [_]u32{ 0x80000000, 0x7FFFFFFF, 0x00000001, }, [_]u32{ 0x80000000, 0x80000000, 0x00000001, }, [_]u32{ 0x80000000, 0xFFFFFFFD, 0x00000000, }, [_]u32{ 0x80000000, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0x80000000, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0xFFFFFFFD, 0x00000001, 0xFFFFFFFD, }, [_]u32{ 0xFFFFFFFD, 0x00000002, 0x7FFFFFFE, }, [_]u32{ 0xFFFFFFFD, 0x00000003, 0x55555554, }, [_]u32{ 0xFFFFFFFD, 0x00000010, 0x0FFFFFFF, }, [_]u32{ 0xFFFFFFFD, 0x078644FA, 0x00000022, }, [_]u32{ 0xFFFFFFFD, 0x0747AE14, 0x00000023, }, [_]u32{ 0xFFFFFFFD, 0x7FFFFFFF, 0x00000001, }, [_]u32{ 0xFFFFFFFD, 0x80000000, 0x00000001, }, [_]u32{ 0xFFFFFFFD, 0xFFFFFFFD, 0x00000001, }, [_]u32{ 0xFFFFFFFD, 0xFFFFFFFE, 0x00000000, }, [_]u32{ 0xFFFFFFFD, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0xFFFFFFFE, 0x00000001, 0xFFFFFFFE, }, [_]u32{ 0xFFFFFFFE, 0x00000002, 0x7FFFFFFF, }, [_]u32{ 0xFFFFFFFE, 0x00000003, 0x55555554, }, [_]u32{ 0xFFFFFFFE, 0x00000010, 0x0FFFFFFF, }, [_]u32{ 0xFFFFFFFE, 0x078644FA, 0x00000022, }, [_]u32{ 0xFFFFFFFE, 0x0747AE14, 0x00000023, }, [_]u32{ 0xFFFFFFFE, 0x7FFFFFFF, 0x00000002, }, [_]u32{ 0xFFFFFFFE, 0x80000000, 0x00000001, }, [_]u32{ 0xFFFFFFFE, 0xFFFFFFFD, 0x00000001, }, [_]u32{ 0xFFFFFFFE, 0xFFFFFFFE, 0x00000001, }, [_]u32{ 0xFFFFFFFE, 0xFFFFFFFF, 0x00000000, }, [_]u32{ 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, }, [_]u32{ 0xFFFFFFFF, 0x00000002, 0x7FFFFFFF, }, [_]u32{ 0xFFFFFFFF, 0x00000003, 0x55555555, }, [_]u32{ 0xFFFFFFFF, 0x00000010, 0x0FFFFFFF, }, [_]u32{ 0xFFFFFFFF, 0x078644FA, 0x00000022, }, [_]u32{ 0xFFFFFFFF, 0x0747AE14, 0x00000023, }, [_]u32{ 0xFFFFFFFF, 0x7FFFFFFF, 0x00000002, }, [_]u32{ 0xFFFFFFFF, 0x80000000, 0x00000001, }, [_]u32{ 0xFFFFFFFF, 0xFFFFFFFD, 0x00000001, }, [_]u32{ 0xFFFFFFFF, 0xFFFFFFFE, 0x00000001, }, [_]u32{ 0xFFFFFFFF, 0xFFFFFFFF, 0x00000001, }, }; for (cases) |case| { test_one_udivsi3(case[0], case[1], case[2]); } } fn test_one_udivsi3(a: u32, b: u32, expected_q: u32) void { const q: u32 = __udivsi3(a, b); testing.expect(q == expected_q); } test "test_divsi3" { const cases = [_][3]i32{ [_]i32{ 0, 1, 0 }, [_]i32{ 0, -1, 0 }, [_]i32{ 2, 1, 2 }, [_]i32{ 2, -1, -2 }, [_]i32{ -2, 1, -2 }, [_]i32{ -2, -1, 2 }, [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 1, @bitCast(i32, @as(u32, 0x80000000)) }, [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), -1, @bitCast(i32, @as(u32, 0x80000000)) }, [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), -2, 0x40000000 }, [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 2, @bitCast(i32, @as(u32, 0xC0000000)) }, }; for (cases) |case| { test_one_divsi3(case[0], case[1], case[2]); } } fn test_one_divsi3(a: i32, b: i32, expected_q: i32) void { const q: i32 = __divsi3(a, b); testing.expect(q == expected_q); } test "test_divmodsi4" { const cases = [_][4]i32{ [_]i32{ 0, 1, 0, 0 }, [_]i32{ 0, -1, 0, 0 }, [_]i32{ 2, 1, 2, 0 }, [_]i32{ 2, -1, -2, 0 }, [_]i32{ -2, 1, -2, 0 }, [_]i32{ -2, -1, 2, 0 }, [_]i32{ 7, 5, 1, 2 }, [_]i32{ -7, 5, -1, -2 }, [_]i32{ 19, 5, 3, 4 }, [_]i32{ 19, -5, -3, 4 }, [_]i32{ @bitCast(i32, @as(u32, 0x80000000)), 8, @bitCast(i32, @as(u32, 0xf0000000)), 0 }, [_]i32{ @bitCast(i32, @as(u32, 0x80000007)), 8, @bitCast(i32, @as(u32, 0xf0000001)), -1 }, }; for (cases) |case| { test_one_divmodsi4(case[0], case[1], case[2], case[3]); } } fn test_one_divmodsi4(a: i32, b: i32, expected_q: i32, expected_r: i32) void { var r: i32 = undefined; const q: i32 = __divmodsi4(a, b, &r); testing.expect(q == expected_q and r == expected_r); } test "test_divdi3" { const cases = [_][3]i64{ [_]i64{ 0, 1, 0 }, [_]i64{ 0, -1, 0 }, [_]i64{ 2, 1, 2 }, [_]i64{ 2, -1, -2 }, [_]i64{ -2, 1, -2 }, [_]i64{ -2, -1, 2 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 1, @bitCast(i64, @as(u64, 0x8000000000000000)) }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -1, @bitCast(i64, @as(u64, 0x8000000000000000)) }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -2, 0x4000000000000000 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 2, @bitCast(i64, @as(u64, 0xC000000000000000)) }, }; for (cases) |case| { test_one_divdi3(case[0], case[1], case[2]); } } fn test_one_divdi3(a: i64, b: i64, expected_q: i64) void { const q: i64 = __divdi3(a, b); testing.expect(q == expected_q); } test "test_moddi3" { const cases = [_][3]i64{ [_]i64{ 0, 1, 0 }, [_]i64{ 0, -1, 0 }, [_]i64{ 5, 3, 2 }, [_]i64{ 5, -3, 2 }, [_]i64{ -5, 3, -2 }, [_]i64{ -5, -3, -2 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 1, 0 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -1, 0 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 2, 0 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -2, 0 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), 3, -2 }, [_]i64{ @bitCast(i64, @as(u64, 0x8000000000000000)), -3, -2 }, }; for (cases) |case| { test_one_moddi3(case[0], case[1], case[2]); } } fn test_one_moddi3(a: i64, b: i64, expected_r: i64) void { const r: i64 = __moddi3(a, b); testing.expect(r == expected_r); } test "test_modsi3" { const cases = [_][3]i32{ [_]i32{ 0, 1, 0 }, [_]i32{ 0, -1, 0 }, [_]i32{ 5, 3, 2 }, [_]i32{ 5, -3, 2 }, [_]i32{ -5, 3, -2 }, [_]i32{ -5, -3, -2 }, [_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), 1, 0x0 }, [_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), 2, 0x0 }, [_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), -2, 0x0 }, [_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), 3, -2 }, [_]i32{ @bitCast(i32, @intCast(u32, 0x80000000)), -3, -2 }, }; for (cases) |case| { test_one_modsi3(case[0], case[1], case[2]); } } fn test_one_modsi3(a: i32, b: i32, expected_r: i32) void { const r: i32 = __modsi3(a, b); testing.expect(r == expected_r); } test "test_umodsi3" { const cases = [_][3]u32{ [_]u32{ 0x00000000, 0x00000001, 0x00000000 }, [_]u32{ 0x00000000, 0x00000002, 0x00000000 }, [_]u32{ 0x00000000, 0x00000003, 0x00000000 }, [_]u32{ 0x00000000, 0x00000010, 0x00000000 }, [_]u32{ 0x00000000, 0x078644FA, 0x00000000 }, [_]u32{ 0x00000000, 0x0747AE14, 0x00000000 }, [_]u32{ 0x00000000, 0x7FFFFFFF, 0x00000000 }, [_]u32{ 0x00000000, 0x80000000, 0x00000000 }, [_]u32{ 0x00000000, 0xFFFFFFFD, 0x00000000 }, [_]u32{ 0x00000000, 0xFFFFFFFE, 0x00000000 }, [_]u32{ 0x00000000, 0xFFFFFFFF, 0x00000000 }, [_]u32{ 0x00000001, 0x00000001, 0x00000000 }, [_]u32{ 0x00000001, 0x00000002, 0x00000001 }, [_]u32{ 0x00000001, 0x00000003, 0x00000001 }, [_]u32{ 0x00000001, 0x00000010, 0x00000001 }, [_]u32{ 0x00000001, 0x078644FA, 0x00000001 }, [_]u32{ 0x00000001, 0x0747AE14, 0x00000001 }, [_]u32{ 0x00000001, 0x7FFFFFFF, 0x00000001 }, [_]u32{ 0x00000001, 0x80000000, 0x00000001 }, [_]u32{ 0x00000001, 0xFFFFFFFD, 0x00000001 }, [_]u32{ 0x00000001, 0xFFFFFFFE, 0x00000001 }, [_]u32{ 0x00000001, 0xFFFFFFFF, 0x00000001 }, [_]u32{ 0x00000002, 0x00000001, 0x00000000 }, [_]u32{ 0x00000002, 0x00000002, 0x00000000 }, [_]u32{ 0x00000002, 0x00000003, 0x00000002 }, [_]u32{ 0x00000002, 0x00000010, 0x00000002 }, [_]u32{ 0x00000002, 0x078644FA, 0x00000002 }, [_]u32{ 0x00000002, 0x0747AE14, 0x00000002 }, [_]u32{ 0x00000002, 0x7FFFFFFF, 0x00000002 }, [_]u32{ 0x00000002, 0x80000000, 0x00000002 }, [_]u32{ 0x00000002, 0xFFFFFFFD, 0x00000002 }, [_]u32{ 0x00000002, 0xFFFFFFFE, 0x00000002 }, [_]u32{ 0x00000002, 0xFFFFFFFF, 0x00000002 }, [_]u32{ 0x00000003, 0x00000001, 0x00000000 }, [_]u32{ 0x00000003, 0x00000002, 0x00000001 }, [_]u32{ 0x00000003, 0x00000003, 0x00000000 }, [_]u32{ 0x00000003, 0x00000010, 0x00000003 }, [_]u32{ 0x00000003, 0x078644FA, 0x00000003 }, [_]u32{ 0x00000003, 0x0747AE14, 0x00000003 }, [_]u32{ 0x00000003, 0x7FFFFFFF, 0x00000003 }, [_]u32{ 0x00000003, 0x80000000, 0x00000003 }, [_]u32{ 0x00000003, 0xFFFFFFFD, 0x00000003 }, [_]u32{ 0x00000003, 0xFFFFFFFE, 0x00000003 }, [_]u32{ 0x00000003, 0xFFFFFFFF, 0x00000003 }, [_]u32{ 0x00000010, 0x00000001, 0x00000000 }, [_]u32{ 0x00000010, 0x00000002, 0x00000000 }, [_]u32{ 0x00000010, 0x00000003, 0x00000001 }, [_]u32{ 0x00000010, 0x00000010, 0x00000000 }, [_]u32{ 0x00000010, 0x078644FA, 0x00000010 }, [_]u32{ 0x00000010, 0x0747AE14, 0x00000010 }, [_]u32{ 0x00000010, 0x7FFFFFFF, 0x00000010 }, [_]u32{ 0x00000010, 0x80000000, 0x00000010 }, [_]u32{ 0x00000010, 0xFFFFFFFD, 0x00000010 }, [_]u32{ 0x00000010, 0xFFFFFFFE, 0x00000010 }, [_]u32{ 0x00000010, 0xFFFFFFFF, 0x00000010 }, [_]u32{ 0x078644FA, 0x00000001, 0x00000000 }, [_]u32{ 0x078644FA, 0x00000002, 0x00000000 }, [_]u32{ 0x078644FA, 0x00000003, 0x00000000 }, [_]u32{ 0x078644FA, 0x00000010, 0x0000000A }, [_]u32{ 0x078644FA, 0x078644FA, 0x00000000 }, [_]u32{ 0x078644FA, 0x0747AE14, 0x003E96E6 }, [_]u32{ 0x078644FA, 0x7FFFFFFF, 0x078644FA }, [_]u32{ 0x078644FA, 0x80000000, 0x078644FA }, [_]u32{ 0x078644FA, 0xFFFFFFFD, 0x078644FA }, [_]u32{ 0x078644FA, 0xFFFFFFFE, 0x078644FA }, [_]u32{ 0x078644FA, 0xFFFFFFFF, 0x078644FA }, [_]u32{ 0x0747AE14, 0x00000001, 0x00000000 }, [_]u32{ 0x0747AE14, 0x00000002, 0x00000000 }, [_]u32{ 0x0747AE14, 0x00000003, 0x00000002 }, [_]u32{ 0x0747AE14, 0x00000010, 0x00000004 }, [_]u32{ 0x0747AE14, 0x078644FA, 0x0747AE14 }, [_]u32{ 0x0747AE14, 0x0747AE14, 0x00000000 }, [_]u32{ 0x0747AE14, 0x7FFFFFFF, 0x0747AE14 }, [_]u32{ 0x0747AE14, 0x80000000, 0x0747AE14 }, [_]u32{ 0x0747AE14, 0xFFFFFFFD, 0x0747AE14 }, [_]u32{ 0x0747AE14, 0xFFFFFFFE, 0x0747AE14 }, [_]u32{ 0x0747AE14, 0xFFFFFFFF, 0x0747AE14 }, [_]u32{ 0x7FFFFFFF, 0x00000001, 0x00000000 }, [_]u32{ 0x7FFFFFFF, 0x00000002, 0x00000001 }, [_]u32{ 0x7FFFFFFF, 0x00000003, 0x00000001 }, [_]u32{ 0x7FFFFFFF, 0x00000010, 0x0000000F }, [_]u32{ 0x7FFFFFFF, 0x078644FA, 0x00156B65 }, [_]u32{ 0x7FFFFFFF, 0x0747AE14, 0x043D70AB }, [_]u32{ 0x7FFFFFFF, 0x7FFFFFFF, 0x00000000 }, [_]u32{ 0x7FFFFFFF, 0x80000000, 0x7FFFFFFF }, [_]u32{ 0x7FFFFFFF, 0xFFFFFFFD, 0x7FFFFFFF }, [_]u32{ 0x7FFFFFFF, 0xFFFFFFFE, 0x7FFFFFFF }, [_]u32{ 0x7FFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF }, [_]u32{ 0x80000000, 0x00000001, 0x00000000 }, [_]u32{ 0x80000000, 0x00000002, 0x00000000 }, [_]u32{ 0x80000000, 0x00000003, 0x00000002 }, [_]u32{ 0x80000000, 0x00000010, 0x00000000 }, [_]u32{ 0x80000000, 0x078644FA, 0x00156B66 }, [_]u32{ 0x80000000, 0x0747AE14, 0x043D70AC }, [_]u32{ 0x80000000, 0x7FFFFFFF, 0x00000001 }, [_]u32{ 0x80000000, 0x80000000, 0x00000000 }, [_]u32{ 0x80000000, 0xFFFFFFFD, 0x80000000 }, [_]u32{ 0x80000000, 0xFFFFFFFE, 0x80000000 }, [_]u32{ 0x80000000, 0xFFFFFFFF, 0x80000000 }, [_]u32{ 0xFFFFFFFD, 0x00000001, 0x00000000 }, [_]u32{ 0xFFFFFFFD, 0x00000002, 0x00000001 }, [_]u32{ 0xFFFFFFFD, 0x00000003, 0x00000001 }, [_]u32{ 0xFFFFFFFD, 0x00000010, 0x0000000D }, [_]u32{ 0xFFFFFFFD, 0x078644FA, 0x002AD6C9 }, [_]u32{ 0xFFFFFFFD, 0x0747AE14, 0x01333341 }, [_]u32{ 0xFFFFFFFD, 0x7FFFFFFF, 0x7FFFFFFE }, [_]u32{ 0xFFFFFFFD, 0x80000000, 0x7FFFFFFD }, [_]u32{ 0xFFFFFFFD, 0xFFFFFFFD, 0x00000000 }, [_]u32{ 0xFFFFFFFD, 0xFFFFFFFE, 0xFFFFFFFD }, [_]u32{ 0xFFFFFFFD, 0xFFFFFFFF, 0xFFFFFFFD }, [_]u32{ 0xFFFFFFFE, 0x00000001, 0x00000000 }, [_]u32{ 0xFFFFFFFE, 0x00000002, 0x00000000 }, [_]u32{ 0xFFFFFFFE, 0x00000003, 0x00000002 }, [_]u32{ 0xFFFFFFFE, 0x00000010, 0x0000000E }, [_]u32{ 0xFFFFFFFE, 0x078644FA, 0x002AD6CA }, [_]u32{ 0xFFFFFFFE, 0x0747AE14, 0x01333342 }, [_]u32{ 0xFFFFFFFE, 0x7FFFFFFF, 0x00000000 }, [_]u32{ 0xFFFFFFFE, 0x80000000, 0x7FFFFFFE }, [_]u32{ 0xFFFFFFFE, 0xFFFFFFFD, 0x00000001 }, [_]u32{ 0xFFFFFFFE, 0xFFFFFFFE, 0x00000000 }, [_]u32{ 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFE }, [_]u32{ 0xFFFFFFFF, 0x00000001, 0x00000000 }, [_]u32{ 0xFFFFFFFF, 0x00000002, 0x00000001 }, [_]u32{ 0xFFFFFFFF, 0x00000003, 0x00000000 }, [_]u32{ 0xFFFFFFFF, 0x00000010, 0x0000000F }, [_]u32{ 0xFFFFFFFF, 0x078644FA, 0x002AD6CB }, [_]u32{ 0xFFFFFFFF, 0x0747AE14, 0x01333343 }, [_]u32{ 0xFFFFFFFF, 0x7FFFFFFF, 0x00000001 }, [_]u32{ 0xFFFFFFFF, 0x80000000, 0x7FFFFFFF }, [_]u32{ 0xFFFFFFFF, 0xFFFFFFFD, 0x00000002 }, [_]u32{ 0xFFFFFFFF, 0xFFFFFFFE, 0x00000001 }, [_]u32{ 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000 }, }; for (cases) |case| { test_one_umodsi3(case[0], case[1], case[2]); } } fn test_one_umodsi3(a: u32, b: u32, expected_r: u32) void { const r: u32 = __umodsi3(a, b); testing.expect(r == expected_r); }
lib/std/special/compiler_rt.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ines = @import("ines.zig"); const mapper = @import("mapper.zig"); const GenericMapper = mapper.GenericMapper; const console_ = @import("console.zig"); const Config = console_.Config; const Console = console_.Console; pub fn Cart(comptime config: Config) type { return struct { const Self = @This(); mapper: GenericMapper(config), rom_loaded: bool, pub fn init() Self { return Self{ .mapper = undefined, .rom_loaded = false, }; } pub fn deinit(self: Self, allocator: *Allocator) void { if (!self.rom_loaded) { return; } self.mapper.deinit(allocator); } pub fn loadRom(self: *Self, allocator: *Allocator, console: *Console(config), info: *ines.RomInfo) !void { if (self.rom_loaded) { self.mapper.deinit(allocator); } std.log.info("Using mapper {:0>3}", .{info.mapper}); const inits = comptime blk: { break :blk mapper.inits(config); }; self.mapper = (try inits[info.mapper](allocator, console, info)) orelse return error{MapperNotImplemented}.MapperNotImplemented; self.rom_loaded = true; info.prg_rom = null; info.chr_rom = null; } pub inline fn cpuCycled(self: *Self) void { if (self.mapper.cpuCycledFn) |f| { f(&self.mapper); } } pub inline fn mirrorNametable(self: Self, addr: u16) u12 { return self.mapper.mirrorNametableFn(self.mapper, addr); } // TODO pub const peekPrg = readPrg; pub inline fn readPrg(self: Self, addr: u16) ?u8 { return self.mapper.readPrgFn(self.mapper, addr); } pub inline fn writePrg(self: *Self, addr: u16, val: u8) void { self.mapper.writePrgFn(&self.mapper, addr, val); } // TODO pub const peekChr = readChr; pub inline fn readChr(self: Self, addr: u16) u8 { return self.mapper.readChrFn(self.mapper, addr); } pub inline fn writeChr(self: *Self, addr: u16, val: u8) void { return self.mapper.writeChrFn(&self.mapper, addr, val); } }; }
src/cart.zig
const builtin = @import("builtin"); const std = @import("../std.zig"); const mem = std.mem; const assert = std.debug.assert; const math = std.math; const maxInt = std.math.maxInt; const native_arch = builtin.cpu.arch; test { if (builtin.os.tag == .windows) { _ = @import("windows/test.zig"); } } pub const advapi32 = @import("windows/advapi32.zig"); pub const kernel32 = @import("windows/kernel32.zig"); pub const ntdll = @import("windows/ntdll.zig"); pub const ole32 = @import("windows/ole32.zig"); pub const psapi = @import("windows/psapi.zig"); pub const shell32 = @import("windows/shell32.zig"); pub const user32 = @import("windows/user32.zig"); pub const ws2_32 = @import("windows/ws2_32.zig"); pub const gdi32 = @import("windows/gdi32.zig"); pub const winmm = @import("windows/winmm.zig"); pub const self_process_handle = @intToPtr(HANDLE, maxInt(usize)); pub const OpenError = error{ IsDir, NotDir, FileNotFound, NoDevice, AccessDenied, PipeBusy, PathAlreadyExists, Unexpected, NameTooLong, WouldBlock, }; pub const OpenFileOptions = struct { access_mask: ACCESS_MASK, dir: ?HANDLE = null, sa: ?*SECURITY_ATTRIBUTES = null, share_access: ULONG = FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, creation: ULONG, io_mode: std.io.ModeOverride, /// If true, tries to open path as a directory. /// Defaults to false. filter: Filter = .file_only, /// If false, tries to open path as a reparse point without dereferencing it. /// Defaults to true. follow_symlinks: bool = true, pub const Filter = enum { /// Causes `OpenFile` to return `error.IsDir` if the opened handle would be a directory. file_only, /// Causes `OpenFile` to return `error.NotDir` if the opened handle would be a file. dir_only, /// `OpenFile` does not discriminate between opening files and directories. any, }; }; pub fn OpenFile(sub_path_w: []const u16, options: OpenFileOptions) OpenError!HANDLE { if (mem.eql(u16, sub_path_w, &[_]u16{'.'}) and options.filter == .file_only) { return error.IsDir; } if (mem.eql(u16, sub_path_w, &[_]u16{ '.', '.' }) and options.filter == .file_only) { return error.IsDir; } var result: HANDLE = undefined; const path_len_bytes = math.cast(u16, sub_path_w.len * 2) catch |err| switch (err) { error.Overflow => return error.NameTooLong, }; var nt_name = UNICODE_STRING{ .Length = path_len_bytes, .MaximumLength = path_len_bytes, .Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w.ptr)), }; var attr = OBJECT_ATTRIBUTES{ .Length = @sizeOf(OBJECT_ATTRIBUTES), .RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(sub_path_w)) null else options.dir, .Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here. .ObjectName = &nt_name, .SecurityDescriptor = if (options.sa) |ptr| ptr.lpSecurityDescriptor else null, .SecurityQualityOfService = null, }; var io: IO_STATUS_BLOCK = undefined; const blocking_flag: ULONG = if (options.io_mode == .blocking) FILE_SYNCHRONOUS_IO_NONALERT else 0; const file_or_dir_flag: ULONG = switch (options.filter) { .file_only => FILE_NON_DIRECTORY_FILE, .dir_only => FILE_DIRECTORY_FILE, .any => 0, }; // If we're not following symlinks, we need to ensure we don't pass in any synchronization flags such as FILE_SYNCHRONOUS_IO_NONALERT. const flags: ULONG = if (options.follow_symlinks) file_or_dir_flag | blocking_flag else file_or_dir_flag | FILE_OPEN_REPARSE_POINT; const rc = ntdll.NtCreateFile( &result, options.access_mask, &attr, &io, null, FILE_ATTRIBUTE_NORMAL, options.share_access, options.creation, flags, null, 0, ); switch (rc) { .SUCCESS => { if (std.io.is_async and options.io_mode == .evented) { _ = CreateIoCompletionPort(result, std.event.Loop.instance.?.os_data.io_port, undefined, undefined) catch undefined; } return result; }, .OBJECT_NAME_INVALID => unreachable, .OBJECT_NAME_NOT_FOUND => return error.FileNotFound, .OBJECT_PATH_NOT_FOUND => return error.FileNotFound, .NO_MEDIA_IN_DEVICE => return error.NoDevice, .INVALID_PARAMETER => unreachable, .SHARING_VIOLATION => return error.AccessDenied, .ACCESS_DENIED => return error.AccessDenied, .PIPE_BUSY => return error.PipeBusy, .OBJECT_PATH_SYNTAX_BAD => unreachable, .OBJECT_NAME_COLLISION => return error.PathAlreadyExists, .FILE_IS_A_DIRECTORY => return error.IsDir, .NOT_A_DIRECTORY => return error.NotDir, else => return unexpectedStatus(rc), } } pub const CreatePipeError = error{Unexpected}; pub fn CreatePipe(rd: *HANDLE, wr: *HANDLE, sattr: *const SECURITY_ATTRIBUTES) CreatePipeError!void { if (kernel32.CreatePipe(rd, wr, sattr, 0) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub fn CreateEventEx(attributes: ?*SECURITY_ATTRIBUTES, name: []const u8, flags: DWORD, desired_access: DWORD) !HANDLE { const nameW = try sliceToPrefixedFileW(name); return CreateEventExW(attributes, nameW.span().ptr, flags, desired_access); } pub fn CreateEventExW(attributes: ?*SECURITY_ATTRIBUTES, nameW: [*:0]const u16, flags: DWORD, desired_access: DWORD) !HANDLE { const handle = kernel32.CreateEventExW(attributes, nameW, flags, desired_access); if (handle) |h| { return h; } else { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub const DeviceIoControlError = error{ AccessDenied, Unexpected }; /// A Zig wrapper around `NtDeviceIoControlFile` and `NtFsControlFile` syscalls. /// It implements similar behavior to `DeviceIoControl` and is meant to serve /// as a direct substitute for that call. /// TODO work out if we need to expose other arguments to the underlying syscalls. pub fn DeviceIoControl( h: HANDLE, ioControlCode: ULONG, in: ?[]const u8, out: ?[]u8, ) DeviceIoControlError!void { // Logic from: https://doxygen.reactos.org/d3/d74/deviceio_8c.html const is_fsctl = (ioControlCode >> 16) == FILE_DEVICE_FILE_SYSTEM; var io: IO_STATUS_BLOCK = undefined; const in_ptr = if (in) |i| i.ptr else null; const in_len = if (in) |i| @intCast(ULONG, i.len) else 0; const out_ptr = if (out) |o| o.ptr else null; const out_len = if (out) |o| @intCast(ULONG, o.len) else 0; const rc = blk: { if (is_fsctl) { break :blk ntdll.NtFsControlFile( h, null, null, null, &io, ioControlCode, in_ptr, in_len, out_ptr, out_len, ); } else { break :blk ntdll.NtDeviceIoControlFile( h, null, null, null, &io, ioControlCode, in_ptr, in_len, out_ptr, out_len, ); } }; switch (rc) { .SUCCESS => {}, .PRIVILEGE_NOT_HELD => return error.AccessDenied, .ACCESS_DENIED => return error.AccessDenied, .INVALID_PARAMETER => unreachable, else => return unexpectedStatus(rc), } } pub fn GetOverlappedResult(h: HANDLE, overlapped: *OVERLAPPED, wait: bool) !DWORD { var bytes: DWORD = undefined; if (kernel32.GetOverlappedResult(h, overlapped, &bytes, @boolToInt(wait)) == 0) { switch (kernel32.GetLastError()) { .IO_INCOMPLETE => if (!wait) return error.WouldBlock else unreachable, else => |err| return unexpectedError(err), } } return bytes; } pub const SetHandleInformationError = error{Unexpected}; pub fn SetHandleInformation(h: HANDLE, mask: DWORD, flags: DWORD) SetHandleInformationError!void { if (kernel32.SetHandleInformation(h, mask, flags) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub const RtlGenRandomError = error{Unexpected}; /// Call RtlGenRandom() instead of CryptGetRandom() on Windows /// https://github.com/rust-lang-nursery/rand/issues/111 /// https://bugzilla.mozilla.org/show_bug.cgi?id=504270 pub fn RtlGenRandom(output: []u8) RtlGenRandomError!void { var total_read: usize = 0; var buff: []u8 = output[0..]; const max_read_size: ULONG = maxInt(ULONG); while (total_read < output.len) { const to_read: ULONG = math.min(buff.len, max_read_size); if (advapi32.RtlGenRandom(buff.ptr, to_read) == 0) { return unexpectedError(kernel32.GetLastError()); } total_read += to_read; buff = buff[to_read..]; } } pub const WaitForSingleObjectError = error{ WaitAbandoned, WaitTimeOut, Unexpected, }; pub fn WaitForSingleObject(handle: HANDLE, milliseconds: DWORD) WaitForSingleObjectError!void { return WaitForSingleObjectEx(handle, milliseconds, false); } pub fn WaitForSingleObjectEx(handle: HANDLE, milliseconds: DWORD, alertable: bool) WaitForSingleObjectError!void { switch (kernel32.WaitForSingleObjectEx(handle, milliseconds, @boolToInt(alertable))) { WAIT_ABANDONED => return error.WaitAbandoned, WAIT_OBJECT_0 => return, WAIT_TIMEOUT => return error.WaitTimeOut, WAIT_FAILED => switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), }, else => return error.Unexpected, } } pub fn WaitForMultipleObjectsEx(handles: []const HANDLE, waitAll: bool, milliseconds: DWORD, alertable: bool) !u32 { assert(handles.len < MAXIMUM_WAIT_OBJECTS); const nCount: DWORD = @intCast(DWORD, handles.len); switch (kernel32.WaitForMultipleObjectsEx( nCount, handles.ptr, @boolToInt(waitAll), milliseconds, @boolToInt(alertable), )) { WAIT_OBJECT_0...WAIT_OBJECT_0 + MAXIMUM_WAIT_OBJECTS => |n| { const handle_index = n - WAIT_OBJECT_0; assert(handle_index < nCount); return handle_index; }, WAIT_ABANDONED_0...WAIT_ABANDONED_0 + MAXIMUM_WAIT_OBJECTS => |n| { const handle_index = n - WAIT_ABANDONED_0; assert(handle_index < nCount); return error.WaitAbandoned; }, WAIT_TIMEOUT => return error.WaitTimeOut, WAIT_FAILED => switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), }, else => return error.Unexpected, } } pub const CreateIoCompletionPortError = error{Unexpected}; pub fn CreateIoCompletionPort( file_handle: HANDLE, existing_completion_port: ?HANDLE, completion_key: usize, concurrent_thread_count: DWORD, ) CreateIoCompletionPortError!HANDLE { const handle = kernel32.CreateIoCompletionPort(file_handle, existing_completion_port, completion_key, concurrent_thread_count) orelse { switch (kernel32.GetLastError()) { .INVALID_PARAMETER => unreachable, else => |err| return unexpectedError(err), } }; return handle; } pub const PostQueuedCompletionStatusError = error{Unexpected}; pub fn PostQueuedCompletionStatus( completion_port: HANDLE, bytes_transferred_count: DWORD, completion_key: usize, lpOverlapped: ?*OVERLAPPED, ) PostQueuedCompletionStatusError!void { if (kernel32.PostQueuedCompletionStatus(completion_port, bytes_transferred_count, completion_key, lpOverlapped) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub const GetQueuedCompletionStatusResult = enum { Normal, Aborted, Cancelled, EOF, }; pub fn GetQueuedCompletionStatus( completion_port: HANDLE, bytes_transferred_count: *DWORD, lpCompletionKey: *usize, lpOverlapped: *?*OVERLAPPED, dwMilliseconds: DWORD, ) GetQueuedCompletionStatusResult { if (kernel32.GetQueuedCompletionStatus( completion_port, bytes_transferred_count, lpCompletionKey, lpOverlapped, dwMilliseconds, ) == FALSE) { switch (kernel32.GetLastError()) { .ABANDONED_WAIT_0 => return GetQueuedCompletionStatusResult.Aborted, .OPERATION_ABORTED => return GetQueuedCompletionStatusResult.Cancelled, .HANDLE_EOF => return GetQueuedCompletionStatusResult.EOF, else => |err| { if (std.debug.runtime_safety) { @setEvalBranchQuota(2500); std.debug.panic("unexpected error: {}\n", .{err}); } }, } } return GetQueuedCompletionStatusResult.Normal; } pub const GetQueuedCompletionStatusError = error{ Aborted, Cancelled, EOF, Timeout, } || std.os.UnexpectedError; pub fn GetQueuedCompletionStatusEx( completion_port: HANDLE, completion_port_entries: []OVERLAPPED_ENTRY, timeout_ms: ?DWORD, alertable: bool, ) GetQueuedCompletionStatusError!u32 { var num_entries_removed: u32 = 0; const success = kernel32.GetQueuedCompletionStatusEx( completion_port, completion_port_entries.ptr, @intCast(ULONG, completion_port_entries.len), &num_entries_removed, timeout_ms orelse INFINITE, @boolToInt(alertable), ); if (success == FALSE) { return switch (kernel32.GetLastError()) { .ABANDONED_WAIT_0 => error.Aborted, .OPERATION_ABORTED => error.Cancelled, .HANDLE_EOF => error.EOF, .IMEOUT => error.Timeout, else => |err| unexpectedError(err), }; } return num_entries_removed; } pub fn CloseHandle(hObject: HANDLE) void { assert(ntdll.NtClose(hObject) == .SUCCESS); } pub fn FindClose(hFindFile: HANDLE) void { assert(kernel32.FindClose(hFindFile) != 0); } pub const ReadFileError = error{ OperationAborted, BrokenPipe, Unexpected, }; /// If buffer's length exceeds what a Windows DWORD integer can hold, it will be broken into /// multiple non-atomic reads. pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64, io_mode: std.io.ModeOverride) ReadFileError!usize { if (io_mode != .blocking) { const loop = std.event.Loop.instance.?; // TODO make getting the file position non-blocking const off = if (offset) |o| o else try SetFilePointerEx_CURRENT_get(in_hFile); var resume_node = std.event.Loop.ResumeNode.Basic{ .base = .{ .id = .Basic, .handle = @frame(), .overlapped = OVERLAPPED{ .Internal = 0, .InternalHigh = 0, .DUMMYUNIONNAME = .{ .DUMMYSTRUCTNAME = .{ .Offset = @truncate(u32, off), .OffsetHigh = @truncate(u32, off >> 32), }, }, .hEvent = null, }, }, }; loop.beginOneEvent(); suspend { // TODO handle buffer bigger than DWORD can hold _ = kernel32.ReadFile(in_hFile, buffer.ptr, @intCast(DWORD, buffer.len), null, &resume_node.base.overlapped); } var bytes_transferred: DWORD = undefined; if (kernel32.GetOverlappedResult(in_hFile, &resume_node.base.overlapped, &bytes_transferred, FALSE) == 0) { switch (kernel32.GetLastError()) { .IO_PENDING => unreachable, .OPERATION_ABORTED => return error.OperationAborted, .BROKEN_PIPE => return error.BrokenPipe, .HANDLE_EOF => return @as(usize, bytes_transferred), else => |err| return unexpectedError(err), } } if (offset == null) { // TODO make setting the file position non-blocking const new_off = off + bytes_transferred; try SetFilePointerEx_CURRENT(in_hFile, @bitCast(i64, new_off)); } return @as(usize, bytes_transferred); } else { while (true) { const want_read_count = @intCast(DWORD, math.min(@as(DWORD, maxInt(DWORD)), buffer.len)); var amt_read: DWORD = undefined; var overlapped_data: OVERLAPPED = undefined; const overlapped: ?*OVERLAPPED = if (offset) |off| blk: { overlapped_data = .{ .Internal = 0, .InternalHigh = 0, .DUMMYUNIONNAME = .{ .DUMMYSTRUCTNAME = .{ .Offset = @truncate(u32, off), .OffsetHigh = @truncate(u32, off >> 32), }, }, .hEvent = null, }; break :blk &overlapped_data; } else null; if (kernel32.ReadFile(in_hFile, buffer.ptr, want_read_count, &amt_read, overlapped) == 0) { switch (kernel32.GetLastError()) { .OPERATION_ABORTED => continue, .BROKEN_PIPE => return 0, .HANDLE_EOF => return 0, else => |err| return unexpectedError(err), } } return amt_read; } } } pub const WriteFileError = error{ SystemResources, OperationAborted, BrokenPipe, NotOpenForWriting, Unexpected, }; pub fn WriteFile( handle: HANDLE, bytes: []const u8, offset: ?u64, io_mode: std.io.ModeOverride, ) WriteFileError!usize { if (std.event.Loop.instance != null and io_mode != .blocking) { const loop = std.event.Loop.instance.?; // TODO make getting the file position non-blocking const off = if (offset) |o| o else try SetFilePointerEx_CURRENT_get(handle); var resume_node = std.event.Loop.ResumeNode.Basic{ .base = .{ .id = .Basic, .handle = @frame(), .overlapped = OVERLAPPED{ .Internal = 0, .InternalHigh = 0, .DUMMYUNIONNAME = .{ .DUMMYSTRUCTNAME = .{ .Offset = @truncate(u32, off), .OffsetHigh = @truncate(u32, off >> 32), }, }, .hEvent = null, }, }, }; loop.beginOneEvent(); suspend { const adjusted_len = math.cast(DWORD, bytes.len) catch maxInt(DWORD); _ = kernel32.WriteFile(handle, bytes.ptr, adjusted_len, null, &resume_node.base.overlapped); } var bytes_transferred: DWORD = undefined; if (kernel32.GetOverlappedResult(handle, &resume_node.base.overlapped, &bytes_transferred, FALSE) == 0) { switch (kernel32.GetLastError()) { .IO_PENDING => unreachable, .INVALID_USER_BUFFER => return error.SystemResources, .NOT_ENOUGH_MEMORY => return error.SystemResources, .OPERATION_ABORTED => return error.OperationAborted, .NOT_ENOUGH_QUOTA => return error.SystemResources, .BROKEN_PIPE => return error.BrokenPipe, else => |err| return unexpectedError(err), } } if (offset == null) { // TODO make setting the file position non-blocking const new_off = off + bytes_transferred; try SetFilePointerEx_CURRENT(handle, @bitCast(i64, new_off)); } return bytes_transferred; } else { var bytes_written: DWORD = undefined; var overlapped_data: OVERLAPPED = undefined; const overlapped: ?*OVERLAPPED = if (offset) |off| blk: { overlapped_data = .{ .Internal = 0, .InternalHigh = 0, .DUMMYUNIONNAME = .{ .DUMMYSTRUCTNAME = .{ .Offset = @truncate(u32, off), .OffsetHigh = @truncate(u32, off >> 32), }, }, .hEvent = null, }; break :blk &overlapped_data; } else null; const adjusted_len = math.cast(u32, bytes.len) catch maxInt(u32); if (kernel32.WriteFile(handle, bytes.ptr, adjusted_len, &bytes_written, overlapped) == 0) { switch (kernel32.GetLastError()) { .INVALID_USER_BUFFER => return error.SystemResources, .NOT_ENOUGH_MEMORY => return error.SystemResources, .OPERATION_ABORTED => return error.OperationAborted, .NOT_ENOUGH_QUOTA => return error.SystemResources, .IO_PENDING => unreachable, .BROKEN_PIPE => return error.BrokenPipe, .INVALID_HANDLE => return error.NotOpenForWriting, else => |err| return unexpectedError(err), } } return bytes_written; } } pub const SetCurrentDirectoryError = error{ NameTooLong, InvalidUtf8, FileNotFound, NotDir, AccessDenied, NoDevice, BadPathName, Unexpected, }; pub fn SetCurrentDirectory(path_name: []const u16) SetCurrentDirectoryError!void { const path_len_bytes = math.cast(u16, path_name.len * 2) catch |err| switch (err) { error.Overflow => return error.NameTooLong, }; var nt_name = UNICODE_STRING{ .Length = path_len_bytes, .MaximumLength = path_len_bytes, .Buffer = @intToPtr([*]u16, @ptrToInt(path_name.ptr)), }; const rc = ntdll.RtlSetCurrentDirectory_U(&nt_name); switch (rc) { .SUCCESS => {}, .OBJECT_NAME_INVALID => return error.BadPathName, .OBJECT_NAME_NOT_FOUND => return error.FileNotFound, .OBJECT_PATH_NOT_FOUND => return error.FileNotFound, .NO_MEDIA_IN_DEVICE => return error.NoDevice, .INVALID_PARAMETER => unreachable, .ACCESS_DENIED => return error.AccessDenied, .OBJECT_PATH_SYNTAX_BAD => unreachable, .NOT_A_DIRECTORY => return error.NotDir, else => return unexpectedStatus(rc), } } pub const GetCurrentDirectoryError = error{ NameTooLong, Unexpected, }; /// The result is a slice of `buffer`, indexed from 0. pub fn GetCurrentDirectory(buffer: []u8) GetCurrentDirectoryError![]u8 { var utf16le_buf: [PATH_MAX_WIDE]u16 = undefined; const result = kernel32.GetCurrentDirectoryW(utf16le_buf.len, &utf16le_buf); if (result == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } assert(result <= utf16le_buf.len); const utf16le_slice = utf16le_buf[0..result]; // Trust that Windows gives us valid UTF-16LE. var end_index: usize = 0; var it = std.unicode.Utf16LeIterator.init(utf16le_slice); while (it.nextCodepoint() catch unreachable) |codepoint| { const seq_len = std.unicode.utf8CodepointSequenceLength(codepoint) catch unreachable; if (end_index + seq_len >= buffer.len) return error.NameTooLong; end_index += std.unicode.utf8Encode(codepoint, buffer[end_index..]) catch unreachable; } return buffer[0..end_index]; } pub const CreateSymbolicLinkError = error{ AccessDenied, PathAlreadyExists, FileNotFound, NameTooLong, NoDevice, Unexpected, }; /// Needs either: /// - `SeCreateSymbolicLinkPrivilege` privilege /// or /// - Developer mode on Windows 10 /// otherwise fails with `error.AccessDenied`. In which case `sym_link_path` may still /// be created on the file system but will lack reparse processing data applied to it. pub fn CreateSymbolicLink( dir: ?HANDLE, sym_link_path: []const u16, target_path: []const u16, is_directory: bool, ) CreateSymbolicLinkError!void { const SYMLINK_DATA = extern struct { ReparseTag: ULONG, ReparseDataLength: USHORT, Reserved: USHORT, SubstituteNameOffset: USHORT, SubstituteNameLength: USHORT, PrintNameOffset: USHORT, PrintNameLength: USHORT, Flags: ULONG, }; const symlink_handle = OpenFile(sym_link_path, .{ .access_mask = SYNCHRONIZE | GENERIC_READ | GENERIC_WRITE, .dir = dir, .creation = FILE_CREATE, .io_mode = .blocking, .filter = if (is_directory) .dir_only else .file_only, }) catch |err| switch (err) { error.IsDir => return error.PathAlreadyExists, error.NotDir => unreachable, error.WouldBlock => unreachable, error.PipeBusy => unreachable, else => |e| return e, }; defer CloseHandle(symlink_handle); // prepare reparse data buffer var buffer: [MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 = undefined; const buf_len = @sizeOf(SYMLINK_DATA) + target_path.len * 4; const header_len = @sizeOf(ULONG) + @sizeOf(USHORT) * 2; const symlink_data = SYMLINK_DATA{ .ReparseTag = IO_REPARSE_TAG_SYMLINK, .ReparseDataLength = @intCast(u16, buf_len - header_len), .Reserved = 0, .SubstituteNameOffset = @intCast(u16, target_path.len * 2), .SubstituteNameLength = @intCast(u16, target_path.len * 2), .PrintNameOffset = 0, .PrintNameLength = @intCast(u16, target_path.len * 2), .Flags = if (dir) |_| SYMLINK_FLAG_RELATIVE else 0, }; std.mem.copy(u8, buffer[0..], std.mem.asBytes(&symlink_data)); @memcpy(buffer[@sizeOf(SYMLINK_DATA)..], @ptrCast([*]const u8, target_path), target_path.len * 2); const paths_start = @sizeOf(SYMLINK_DATA) + target_path.len * 2; @memcpy(buffer[paths_start..].ptr, @ptrCast([*]const u8, target_path), target_path.len * 2); _ = try DeviceIoControl(symlink_handle, FSCTL_SET_REPARSE_POINT, buffer[0..buf_len], null); } pub const ReadLinkError = error{ FileNotFound, AccessDenied, Unexpected, NameTooLong, UnsupportedReparsePointType, }; pub fn ReadLink(dir: ?HANDLE, sub_path_w: []const u16, out_buffer: []u8) ReadLinkError![]u8 { // Here, we use `NtCreateFile` to shave off one syscall if we were to use `OpenFile` wrapper. // With the latter, we'd need to call `NtCreateFile` twice, once for file symlink, and if that // failed, again for dir symlink. Omitting any mention of file/dir flags makes it possible // to open the symlink there and then. const path_len_bytes = math.cast(u16, sub_path_w.len * 2) catch |err| switch (err) { error.Overflow => return error.NameTooLong, }; var nt_name = UNICODE_STRING{ .Length = path_len_bytes, .MaximumLength = path_len_bytes, .Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w.ptr)), }; var attr = OBJECT_ATTRIBUTES{ .Length = @sizeOf(OBJECT_ATTRIBUTES), .RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(sub_path_w)) null else dir, .Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here. .ObjectName = &nt_name, .SecurityDescriptor = null, .SecurityQualityOfService = null, }; var result_handle: HANDLE = undefined; var io: IO_STATUS_BLOCK = undefined; const rc = ntdll.NtCreateFile( &result_handle, FILE_READ_ATTRIBUTES, &attr, &io, null, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, FILE_OPEN_REPARSE_POINT, null, 0, ); switch (rc) { .SUCCESS => {}, .OBJECT_NAME_INVALID => unreachable, .OBJECT_NAME_NOT_FOUND => return error.FileNotFound, .OBJECT_PATH_NOT_FOUND => return error.FileNotFound, .NO_MEDIA_IN_DEVICE => return error.FileNotFound, .INVALID_PARAMETER => unreachable, .SHARING_VIOLATION => return error.AccessDenied, .ACCESS_DENIED => return error.AccessDenied, .PIPE_BUSY => return error.AccessDenied, .OBJECT_PATH_SYNTAX_BAD => unreachable, .OBJECT_NAME_COLLISION => unreachable, .FILE_IS_A_DIRECTORY => unreachable, else => return unexpectedStatus(rc), } defer CloseHandle(result_handle); var reparse_buf: [MAXIMUM_REPARSE_DATA_BUFFER_SIZE]u8 = undefined; _ = DeviceIoControl(result_handle, FSCTL_GET_REPARSE_POINT, null, reparse_buf[0..]) catch |err| switch (err) { error.AccessDenied => unreachable, else => |e| return e, }; const reparse_struct = @ptrCast(*const REPARSE_DATA_BUFFER, @alignCast(@alignOf(REPARSE_DATA_BUFFER), &reparse_buf[0])); switch (reparse_struct.ReparseTag) { IO_REPARSE_TAG_SYMLINK => { const buf = @ptrCast(*const SYMBOLIC_LINK_REPARSE_BUFFER, @alignCast(@alignOf(SYMBOLIC_LINK_REPARSE_BUFFER), &reparse_struct.DataBuffer[0])); const offset = buf.SubstituteNameOffset >> 1; const len = buf.SubstituteNameLength >> 1; const path_buf = @as([*]const u16, &buf.PathBuffer); const is_relative = buf.Flags & SYMLINK_FLAG_RELATIVE != 0; return parseReadlinkPath(path_buf[offset .. offset + len], is_relative, out_buffer); }, IO_REPARSE_TAG_MOUNT_POINT => { const buf = @ptrCast(*const MOUNT_POINT_REPARSE_BUFFER, @alignCast(@alignOf(MOUNT_POINT_REPARSE_BUFFER), &reparse_struct.DataBuffer[0])); const offset = buf.SubstituteNameOffset >> 1; const len = buf.SubstituteNameLength >> 1; const path_buf = @as([*]const u16, &buf.PathBuffer); return parseReadlinkPath(path_buf[offset .. offset + len], false, out_buffer); }, else => |value| { std.debug.print("unsupported symlink type: {}", .{value}); return error.UnsupportedReparsePointType; }, } } fn parseReadlinkPath(path: []const u16, is_relative: bool, out_buffer: []u8) []u8 { const prefix = [_]u16{ '\\', '?', '?', '\\' }; var start_index: usize = 0; if (!is_relative and std.mem.startsWith(u16, path, &prefix)) { start_index = prefix.len; } const out_len = std.unicode.utf16leToUtf8(out_buffer, path[start_index..]) catch unreachable; return out_buffer[0..out_len]; } pub const DeleteFileError = error{ FileNotFound, AccessDenied, NameTooLong, /// Also known as sharing violation. FileBusy, Unexpected, NotDir, IsDir, }; pub const DeleteFileOptions = struct { dir: ?HANDLE, remove_dir: bool = false, }; pub fn DeleteFile(sub_path_w: []const u16, options: DeleteFileOptions) DeleteFileError!void { const create_options_flags: ULONG = if (options.remove_dir) FILE_DELETE_ON_CLOSE | FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT else FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT; // would we ever want to delete the target instead? const path_len_bytes = @intCast(u16, sub_path_w.len * 2); var nt_name = UNICODE_STRING{ .Length = path_len_bytes, .MaximumLength = path_len_bytes, // The Windows API makes this mutable, but it will not mutate here. .Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w.ptr)), }; if (sub_path_w[0] == '.' and sub_path_w[1] == 0) { // Windows does not recognize this, but it does work with empty string. nt_name.Length = 0; } if (sub_path_w[0] == '.' and sub_path_w[1] == '.' and sub_path_w[2] == 0) { // Can't remove the parent directory with an open handle. return error.FileBusy; } var attr = OBJECT_ATTRIBUTES{ .Length = @sizeOf(OBJECT_ATTRIBUTES), .RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(sub_path_w)) null else options.dir, .Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here. .ObjectName = &nt_name, .SecurityDescriptor = null, .SecurityQualityOfService = null, }; var io: IO_STATUS_BLOCK = undefined; var tmp_handle: HANDLE = undefined; var rc = ntdll.NtCreateFile( &tmp_handle, SYNCHRONIZE | DELETE, &attr, &io, null, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN, create_options_flags, null, 0, ); switch (rc) { .SUCCESS => return CloseHandle(tmp_handle), .OBJECT_NAME_INVALID => unreachable, .OBJECT_NAME_NOT_FOUND => return error.FileNotFound, .OBJECT_PATH_NOT_FOUND => return error.FileNotFound, .INVALID_PARAMETER => unreachable, .FILE_IS_A_DIRECTORY => return error.IsDir, .NOT_A_DIRECTORY => return error.NotDir, .SHARING_VIOLATION => return error.FileBusy, else => return unexpectedStatus(rc), } } pub const MoveFileError = error{ FileNotFound, AccessDenied, Unexpected }; pub fn MoveFileEx(old_path: []const u8, new_path: []const u8, flags: DWORD) MoveFileError!void { const old_path_w = try sliceToPrefixedFileW(old_path); const new_path_w = try sliceToPrefixedFileW(new_path); return MoveFileExW(old_path_w.span().ptr, new_path_w.span().ptr, flags); } pub fn MoveFileExW(old_path: [*:0]const u16, new_path: [*:0]const u16, flags: DWORD) MoveFileError!void { if (kernel32.MoveFileExW(old_path, new_path, flags) == 0) { switch (kernel32.GetLastError()) { .FILE_NOT_FOUND => return error.FileNotFound, .ACCESS_DENIED => return error.AccessDenied, else => |err| return unexpectedError(err), } } } pub const GetStdHandleError = error{ NoStandardHandleAttached, Unexpected, }; pub fn GetStdHandle(handle_id: DWORD) GetStdHandleError!HANDLE { const handle = kernel32.GetStdHandle(handle_id) orelse return error.NoStandardHandleAttached; if (handle == INVALID_HANDLE_VALUE) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } return handle; } pub const SetFilePointerError = error{Unexpected}; /// The SetFilePointerEx function with the `dwMoveMethod` parameter set to `FILE_BEGIN`. pub fn SetFilePointerEx_BEGIN(handle: HANDLE, offset: u64) SetFilePointerError!void { // "The starting point is zero or the beginning of the file. If [FILE_BEGIN] // is specified, then the liDistanceToMove parameter is interpreted as an unsigned value." // https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-setfilepointerex const ipos = @bitCast(LARGE_INTEGER, offset); if (kernel32.SetFilePointerEx(handle, ipos, null, FILE_BEGIN) == 0) { switch (kernel32.GetLastError()) { .INVALID_PARAMETER => unreachable, .INVALID_HANDLE => unreachable, else => |err| return unexpectedError(err), } } } /// The SetFilePointerEx function with the `dwMoveMethod` parameter set to `FILE_CURRENT`. pub fn SetFilePointerEx_CURRENT(handle: HANDLE, offset: i64) SetFilePointerError!void { if (kernel32.SetFilePointerEx(handle, offset, null, FILE_CURRENT) == 0) { switch (kernel32.GetLastError()) { .INVALID_PARAMETER => unreachable, .INVALID_HANDLE => unreachable, else => |err| return unexpectedError(err), } } } /// The SetFilePointerEx function with the `dwMoveMethod` parameter set to `FILE_END`. pub fn SetFilePointerEx_END(handle: HANDLE, offset: i64) SetFilePointerError!void { if (kernel32.SetFilePointerEx(handle, offset, null, FILE_END) == 0) { switch (kernel32.GetLastError()) { .INVALID_PARAMETER => unreachable, .INVALID_HANDLE => unreachable, else => |err| return unexpectedError(err), } } } /// The SetFilePointerEx function with parameters to get the current offset. pub fn SetFilePointerEx_CURRENT_get(handle: HANDLE) SetFilePointerError!u64 { var result: LARGE_INTEGER = undefined; if (kernel32.SetFilePointerEx(handle, 0, &result, FILE_CURRENT) == 0) { switch (kernel32.GetLastError()) { .INVALID_PARAMETER => unreachable, .INVALID_HANDLE => unreachable, else => |err| return unexpectedError(err), } } // Based on the docs for FILE_BEGIN, it seems that the returned signed integer // should be interpreted as an unsigned integer. return @bitCast(u64, result); } pub fn QueryObjectName( handle: HANDLE, out_buffer: []u16, ) ![]u16 { const out_buffer_aligned = mem.alignInSlice(out_buffer, @alignOf(OBJECT_NAME_INFORMATION)) orelse return error.NameTooLong; const info = @ptrCast(*OBJECT_NAME_INFORMATION, out_buffer_aligned); //buffer size is specified in bytes const out_buffer_len = std.math.cast(ULONG, out_buffer_aligned.len * 2) catch |e| switch (e) { error.Overflow => std.math.maxInt(ULONG), }; //last argument would return the length required for full_buffer, not exposed here const rc = ntdll.NtQueryObject(handle, .ObjectNameInformation, info, out_buffer_len, null); switch (rc) { .SUCCESS => { // info.Name.Buffer from ObQueryNameString is documented to be null (and MaximumLength == 0) // if the object was "unnamed", not sure if this can happen for file handles if (info.Name.MaximumLength == 0) return error.Unexpected; // resulting string length is specified in bytes const path_length_unterminated = @divExact(info.Name.Length, 2); return info.Name.Buffer[0..path_length_unterminated]; }, .ACCESS_DENIED => return error.AccessDenied, .INVALID_HANDLE => return error.InvalidHandle, // triggered when the buffer is too small for the OBJECT_NAME_INFORMATION object (.INFO_LENGTH_MISMATCH), // or if the buffer is too small for the file path returned (.BUFFER_OVERFLOW, .BUFFER_TOO_SMALL) .INFO_LENGTH_MISMATCH, .BUFFER_OVERFLOW, .BUFFER_TOO_SMALL => return error.NameTooLong, else => |e| return unexpectedStatus(e), } } test "QueryObjectName" { if (builtin.os.tag != .windows) return; //any file will do; canonicalization works on NTFS junctions and symlinks, hardlinks remain separate paths. var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const handle = tmp.dir.fd; var out_buffer: [PATH_MAX_WIDE]u16 = undefined; var result_path = try QueryObjectName(handle, &out_buffer); const required_len_in_u16 = result_path.len + @divExact(@ptrToInt(result_path.ptr) - @ptrToInt(&out_buffer), 2) + 1; //insufficient size try std.testing.expectError(error.NameTooLong, QueryObjectName(handle, out_buffer[0 .. required_len_in_u16 - 1])); //exactly-sufficient size _ = try QueryObjectName(handle, out_buffer[0..required_len_in_u16]); } pub const GetFinalPathNameByHandleError = error{ AccessDenied, BadPathName, FileNotFound, NameTooLong, Unexpected, }; /// Specifies how to format volume path in the result of `GetFinalPathNameByHandle`. /// Defaults to DOS volume names. pub const GetFinalPathNameByHandleFormat = struct { volume_name: enum { /// Format as DOS volume name Dos, /// Format as NT volume name Nt, } = .Dos, }; /// Returns canonical (normalized) path of handle. /// Use `GetFinalPathNameByHandleFormat` to specify whether the path is meant to include /// NT or DOS volume name (e.g., `\Device\HarddiskVolume0\foo.txt` versus `C:\foo.txt`). /// If DOS volume name format is selected, note that this function does *not* prepend /// `\\?\` prefix to the resultant path. pub fn GetFinalPathNameByHandle( hFile: HANDLE, fmt: GetFinalPathNameByHandleFormat, out_buffer: []u16, ) GetFinalPathNameByHandleError![]u16 { const final_path = QueryObjectName(hFile, out_buffer) catch |err| switch (err) { // we assume InvalidHandle is close enough to FileNotFound in semantics // to not further complicate the error set error.InvalidHandle => return error.FileNotFound, else => |e| return e, }; switch (fmt.volume_name) { .Nt => { // the returned path is already in .Nt format return final_path; }, .Dos => { // parse the string to separate volume path from file path const expected_prefix = std.unicode.utf8ToUtf16LeStringLiteral("\\Device\\"); // TODO find out if a path can start with something besides `\Device\<volume name>`, // and if we need to handle it differently // (i.e. how to determine the start and end of the volume name in that case) if (!mem.eql(u16, expected_prefix, final_path[0..expected_prefix.len])) return error.Unexpected; const file_path_begin_index = mem.indexOfPos(u16, final_path, expected_prefix.len, &[_]u16{'\\'}) orelse unreachable; const volume_name_u16 = final_path[0..file_path_begin_index]; const file_name_u16 = final_path[file_path_begin_index..]; // Get DOS volume name. DOS volume names are actually symbolic link objects to the // actual NT volume. For example: // (NT) \Device\HarddiskVolume4 => (DOS) \DosDevices\C: == (DOS) C: const MIN_SIZE = @sizeOf(MOUNTMGR_MOUNT_POINT) + MAX_PATH; // We initialize the input buffer to all zeros for convenience since // `DeviceIoControl` with `IOCTL_MOUNTMGR_QUERY_POINTS` expects this. var input_buf: [MIN_SIZE]u8 align(@alignOf(MOUNTMGR_MOUNT_POINT)) = [_]u8{0} ** MIN_SIZE; var output_buf: [MIN_SIZE * 4]u8 align(@alignOf(MOUNTMGR_MOUNT_POINTS)) = undefined; // This surprising path is a filesystem path to the mount manager on Windows. // Source: https://stackoverflow.com/questions/3012828/using-ioctl-mountmgr-query-points const mgmt_path = "\\MountPointManager"; const mgmt_path_u16 = sliceToPrefixedFileW(mgmt_path) catch unreachable; const mgmt_handle = OpenFile(mgmt_path_u16.span(), .{ .access_mask = SYNCHRONIZE, .share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, .creation = FILE_OPEN, .io_mode = .blocking, }) catch |err| switch (err) { error.IsDir => unreachable, error.NotDir => unreachable, error.NoDevice => unreachable, error.AccessDenied => unreachable, error.PipeBusy => unreachable, error.PathAlreadyExists => unreachable, error.WouldBlock => unreachable, else => |e| return e, }; defer CloseHandle(mgmt_handle); var input_struct = @ptrCast(*MOUNTMGR_MOUNT_POINT, &input_buf[0]); input_struct.DeviceNameOffset = @sizeOf(MOUNTMGR_MOUNT_POINT); input_struct.DeviceNameLength = @intCast(USHORT, volume_name_u16.len * 2); @memcpy(input_buf[@sizeOf(MOUNTMGR_MOUNT_POINT)..], @ptrCast([*]const u8, volume_name_u16.ptr), volume_name_u16.len * 2); DeviceIoControl(mgmt_handle, IOCTL_MOUNTMGR_QUERY_POINTS, &input_buf, &output_buf) catch |err| switch (err) { error.AccessDenied => unreachable, else => |e| return e, }; const mount_points_struct = @ptrCast(*const MOUNTMGR_MOUNT_POINTS, &output_buf[0]); const mount_points = @ptrCast( [*]const MOUNTMGR_MOUNT_POINT, &mount_points_struct.MountPoints[0], )[0..mount_points_struct.NumberOfMountPoints]; for (mount_points) |mount_point| { const symlink = @ptrCast( [*]const u16, @alignCast(@alignOf(u16), &output_buf[mount_point.SymbolicLinkNameOffset]), )[0 .. mount_point.SymbolicLinkNameLength / 2]; // Look for `\DosDevices\` prefix. We don't really care if there are more than one symlinks // with traditional DOS drive letters, so pick the first one available. var prefix_buf = std.unicode.utf8ToUtf16LeStringLiteral("\\DosDevices\\"); const prefix = prefix_buf[0..prefix_buf.len]; if (mem.startsWith(u16, symlink, prefix)) { const drive_letter = symlink[prefix.len..]; if (out_buffer.len < drive_letter.len + file_name_u16.len) return error.NameTooLong; mem.copy(u16, out_buffer, drive_letter); mem.copy(u16, out_buffer[drive_letter.len..], file_name_u16); const total_len = drive_letter.len + file_name_u16.len; // Validate that DOS does not contain any spurious nul bytes. if (mem.indexOfScalar(u16, out_buffer[0..total_len], 0)) |_| { return error.BadPathName; } return out_buffer[0..total_len]; } } // If we've ended up here, then something went wrong/is corrupted in the OS, // so error out! return error.FileNotFound; }, } } test "GetFinalPathNameByHandle" { if (builtin.os.tag != .windows) return; //any file will do var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const handle = tmp.dir.fd; var buffer: [PATH_MAX_WIDE]u16 = undefined; //check with sufficient size const nt_path = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, &buffer); _ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, &buffer); const required_len_in_u16 = nt_path.len + @divExact(@ptrToInt(nt_path.ptr) - @ptrToInt(&buffer), 2) + 1; //check with insufficient size try std.testing.expectError(error.NameTooLong, GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, buffer[0 .. required_len_in_u16 - 1])); try std.testing.expectError(error.NameTooLong, GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, buffer[0 .. required_len_in_u16 - 1])); //check with exactly-sufficient size _ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Nt }, buffer[0..required_len_in_u16]); _ = try GetFinalPathNameByHandle(handle, .{ .volume_name = .Dos }, buffer[0..required_len_in_u16]); } pub const QueryInformationFileError = error{Unexpected}; pub fn QueryInformationFile( handle: HANDLE, info_class: FILE_INFORMATION_CLASS, out_buffer: []u8, ) QueryInformationFileError!void { var io: IO_STATUS_BLOCK = undefined; const len_bytes = std.math.cast(u32, out_buffer.len) catch unreachable; const rc = ntdll.NtQueryInformationFile(handle, &io, out_buffer.ptr, len_bytes, info_class); switch (rc) { .SUCCESS => {}, .INVALID_PARAMETER => unreachable, else => return unexpectedStatus(rc), } } pub const GetFileSizeError = error{Unexpected}; pub fn GetFileSizeEx(hFile: HANDLE) GetFileSizeError!u64 { var file_size: LARGE_INTEGER = undefined; if (kernel32.GetFileSizeEx(hFile, &file_size) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } return @bitCast(u64, file_size); } pub const GetFileAttributesError = error{ FileNotFound, PermissionDenied, Unexpected, }; pub fn GetFileAttributes(filename: []const u8) GetFileAttributesError!DWORD { const filename_w = try sliceToPrefixedFileW(filename); return GetFileAttributesW(filename_w.span().ptr); } pub fn GetFileAttributesW(lpFileName: [*:0]const u16) GetFileAttributesError!DWORD { const rc = kernel32.GetFileAttributesW(lpFileName); if (rc == INVALID_FILE_ATTRIBUTES) { switch (kernel32.GetLastError()) { .FILE_NOT_FOUND => return error.FileNotFound, .PATH_NOT_FOUND => return error.FileNotFound, .ACCESS_DENIED => return error.PermissionDenied, else => |err| return unexpectedError(err), } } return rc; } pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA { var wsadata: ws2_32.WSADATA = undefined; return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) { 0 => wsadata, else => |err_int| switch (@intToEnum(ws2_32.WinsockError, @intCast(u16, err_int))) { .WSASYSNOTREADY => return error.SystemNotAvailable, .WSAVERNOTSUPPORTED => return error.VersionNotSupported, .WSAEINPROGRESS => return error.BlockingOperationInProgress, .WSAEPROCLIM => return error.ProcessFdQuotaExceeded, else => |err| return unexpectedWSAError(err), }, }; } pub fn WSACleanup() !void { return switch (ws2_32.WSACleanup()) { 0 => {}, ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) { .WSANOTINITIALISED => return error.NotInitialized, .WSAENETDOWN => return error.NetworkNotAvailable, .WSAEINPROGRESS => return error.BlockingOperationInProgress, else => |err| return unexpectedWSAError(err), }, else => unreachable, }; } var wsa_startup_mutex: std.Thread.Mutex = .{}; /// Microsoft requires WSAStartup to be called to initialize, or else /// WSASocketW will return WSANOTINITIALISED. /// Since this is a standard library, we do not have the luxury of /// putting initialization code anywhere, because we would not want /// to pay the cost of calling WSAStartup if there ended up being no /// networking. Also, if Zig code is used as a library, Zig is not in /// charge of the start code, and we couldn't put in any initialization /// code even if we wanted to. /// The documentation for WSAStartup mentions that there must be a /// matching WSACleanup call. It is not possible for the Zig Standard /// Library to honor this for the same reason - there is nowhere to put /// deinitialization code. /// So, API users of the zig std lib have two options: /// * (recommended) The simple, cross-platform way: just call `WSASocketW` /// and don't worry about it. Zig will call WSAStartup() in a thread-safe /// manner and never deinitialize networking. This is ideal for an /// application which has the capability to do networking. /// * The getting-your-hands-dirty way: call `WSAStartup()` before doing /// networking, so that the error handling code for WSANOTINITIALISED never /// gets run, which then allows the application or library to call `WSACleanup()`. /// This could make sense for a library, which has init and deinit /// functions for the whole library's lifetime. pub fn WSASocketW( af: i32, socket_type: i32, protocol: i32, protocolInfo: ?*ws2_32.WSAPROTOCOL_INFOW, g: ws2_32.GROUP, dwFlags: DWORD, ) !ws2_32.SOCKET { var first = true; while (true) { const rc = ws2_32.WSASocketW(af, socket_type, protocol, protocolInfo, g, dwFlags); if (rc == ws2_32.INVALID_SOCKET) { switch (ws2_32.WSAGetLastError()) { .WSAEAFNOSUPPORT => return error.AddressFamilyNotSupported, .WSAEMFILE => return error.ProcessFdQuotaExceeded, .WSAENOBUFS => return error.SystemResources, .WSAEPROTONOSUPPORT => return error.ProtocolNotSupported, .WSANOTINITIALISED => { if (!first) return error.Unexpected; first = false; wsa_startup_mutex.lock(); defer wsa_startup_mutex.unlock(); // Here we could use a flag to prevent multiple threads to prevent // multiple calls to WSAStartup, but it doesn't matter. We're globally // leaking the resource intentionally, and the mutex already prevents // data races within the WSAStartup function. _ = WSAStartup(2, 2) catch |err| switch (err) { error.SystemNotAvailable => return error.SystemResources, error.VersionNotSupported => return error.Unexpected, error.BlockingOperationInProgress => return error.Unexpected, error.ProcessFdQuotaExceeded => return error.ProcessFdQuotaExceeded, error.Unexpected => return error.Unexpected, }; continue; }, else => |err| return unexpectedWSAError(err), } } return rc; } } pub fn bind(s: ws2_32.SOCKET, name: *const ws2_32.sockaddr, namelen: ws2_32.socklen_t) i32 { return ws2_32.bind(s, name, @intCast(i32, namelen)); } pub fn listen(s: ws2_32.SOCKET, backlog: u31) i32 { return ws2_32.listen(s, backlog); } pub fn closesocket(s: ws2_32.SOCKET) !void { switch (ws2_32.closesocket(s)) { 0 => {}, ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) { else => |err| return unexpectedWSAError(err), }, else => unreachable, } } pub fn accept(s: ws2_32.SOCKET, name: ?*ws2_32.sockaddr, namelen: ?*ws2_32.socklen_t) ws2_32.SOCKET { assert((name == null) == (namelen == null)); return ws2_32.accept(s, name, @ptrCast(?*i32, namelen)); } pub fn getsockname(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 { return ws2_32.getsockname(s, name, @ptrCast(*i32, namelen)); } pub fn getpeername(s: ws2_32.SOCKET, name: *ws2_32.sockaddr, namelen: *ws2_32.socklen_t) i32 { return ws2_32.getpeername(s, name, @ptrCast(*i32, namelen)); } pub fn sendmsg( s: ws2_32.SOCKET, msg: *const ws2_32.WSAMSG, flags: u32, ) i32 { var bytes_send: DWORD = undefined; if (ws2_32.WSASendMsg(s, msg, flags, &bytes_send, null, null) == ws2_32.SOCKET_ERROR) { return ws2_32.SOCKET_ERROR; } else { return @as(i32, @intCast(u31, bytes_send)); } } pub fn sendto(s: ws2_32.SOCKET, buf: [*]const u8, len: usize, flags: u32, to: ?*const ws2_32.sockaddr, to_len: ws2_32.socklen_t) i32 { var buffer = ws2_32.WSABUF{ .len = @truncate(u31, len), .buf = @intToPtr([*]u8, @ptrToInt(buf)) }; var bytes_send: DWORD = undefined; if (ws2_32.WSASendTo(s, @ptrCast([*]ws2_32.WSABUF, &buffer), 1, &bytes_send, flags, to, @intCast(i32, to_len), null, null) == ws2_32.SOCKET_ERROR) { return ws2_32.SOCKET_ERROR; } else { return @as(i32, @intCast(u31, bytes_send)); } } pub fn recvfrom(s: ws2_32.SOCKET, buf: [*]u8, len: usize, flags: u32, from: ?*ws2_32.sockaddr, from_len: ?*ws2_32.socklen_t) i32 { var buffer = ws2_32.WSABUF{ .len = @truncate(u31, len), .buf = buf }; var bytes_received: DWORD = undefined; var flags_inout = flags; if (ws2_32.WSARecvFrom(s, @ptrCast([*]ws2_32.WSABUF, &buffer), 1, &bytes_received, &flags_inout, from, @ptrCast(?*i32, from_len), null, null) == ws2_32.SOCKET_ERROR) { return ws2_32.SOCKET_ERROR; } else { return @as(i32, @intCast(u31, bytes_received)); } } pub fn poll(fds: [*]ws2_32.pollfd, n: c_ulong, timeout: i32) i32 { return ws2_32.WSAPoll(fds, n, timeout); } pub fn WSAIoctl( s: ws2_32.SOCKET, dwIoControlCode: DWORD, inBuffer: ?[]const u8, outBuffer: []u8, overlapped: ?*OVERLAPPED, completionRoutine: ?ws2_32.LPWSAOVERLAPPED_COMPLETION_ROUTINE, ) !DWORD { var bytes: DWORD = undefined; switch (ws2_32.WSAIoctl( s, dwIoControlCode, if (inBuffer) |i| i.ptr else null, if (inBuffer) |i| @intCast(DWORD, i.len) else 0, outBuffer.ptr, @intCast(DWORD, outBuffer.len), &bytes, overlapped, completionRoutine, )) { 0 => {}, ws2_32.SOCKET_ERROR => switch (ws2_32.WSAGetLastError()) { else => |err| return unexpectedWSAError(err), }, else => unreachable, } return bytes; } const GetModuleFileNameError = error{Unexpected}; pub fn GetModuleFileNameW(hModule: ?HMODULE, buf_ptr: [*]u16, buf_len: DWORD) GetModuleFileNameError![:0]u16 { const rc = kernel32.GetModuleFileNameW(hModule, buf_ptr, buf_len); if (rc == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } return buf_ptr[0..rc :0]; } pub const TerminateProcessError = error{Unexpected}; pub fn TerminateProcess(hProcess: HANDLE, uExitCode: UINT) TerminateProcessError!void { if (kernel32.TerminateProcess(hProcess, uExitCode) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub const VirtualAllocError = error{Unexpected}; pub fn VirtualAlloc(addr: ?LPVOID, size: usize, alloc_type: DWORD, flProtect: DWORD) VirtualAllocError!LPVOID { return kernel32.VirtualAlloc(addr, size, alloc_type, flProtect) orelse { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } }; } pub fn VirtualFree(lpAddress: ?LPVOID, dwSize: usize, dwFreeType: DWORD) void { assert(kernel32.VirtualFree(lpAddress, dwSize, dwFreeType) != 0); } pub const SetConsoleTextAttributeError = error{Unexpected}; pub fn SetConsoleTextAttribute(hConsoleOutput: HANDLE, wAttributes: WORD) SetConsoleTextAttributeError!void { if (kernel32.SetConsoleTextAttribute(hConsoleOutput, wAttributes) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub fn SetConsoleCtrlHandler(handler_routine: ?HANDLER_ROUTINE, add: bool) !void { const success = kernel32.SetConsoleCtrlHandler( handler_routine, if (add) TRUE else FALSE, ); if (success == FALSE) { return switch (kernel32.GetLastError()) { else => |err| unexpectedError(err), }; } } pub fn SetFileCompletionNotificationModes(handle: HANDLE, flags: UCHAR) !void { const success = kernel32.SetFileCompletionNotificationModes(handle, flags); if (success == FALSE) { return switch (kernel32.GetLastError()) { else => |err| unexpectedError(err), }; } } pub const GetEnvironmentStringsError = error{OutOfMemory}; pub fn GetEnvironmentStringsW() GetEnvironmentStringsError![*:0]u16 { return kernel32.GetEnvironmentStringsW() orelse return error.OutOfMemory; } pub fn FreeEnvironmentStringsW(penv: [*:0]u16) void { assert(kernel32.FreeEnvironmentStringsW(penv) != 0); } pub const GetEnvironmentVariableError = error{ EnvironmentVariableNotFound, Unexpected, }; pub fn GetEnvironmentVariableW(lpName: LPWSTR, lpBuffer: [*]u16, nSize: DWORD) GetEnvironmentVariableError!DWORD { const rc = kernel32.GetEnvironmentVariableW(lpName, lpBuffer, nSize); if (rc == 0) { switch (kernel32.GetLastError()) { .ENVVAR_NOT_FOUND => return error.EnvironmentVariableNotFound, else => |err| return unexpectedError(err), } } return rc; } pub const CreateProcessError = error{ FileNotFound, AccessDenied, InvalidName, Unexpected, }; pub fn CreateProcessW( lpApplicationName: ?LPWSTR, lpCommandLine: LPWSTR, lpProcessAttributes: ?*SECURITY_ATTRIBUTES, lpThreadAttributes: ?*SECURITY_ATTRIBUTES, bInheritHandles: BOOL, dwCreationFlags: DWORD, lpEnvironment: ?*anyopaque, lpCurrentDirectory: ?LPWSTR, lpStartupInfo: *STARTUPINFOW, lpProcessInformation: *PROCESS_INFORMATION, ) CreateProcessError!void { if (kernel32.CreateProcessW( lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, ) == 0) { switch (kernel32.GetLastError()) { .FILE_NOT_FOUND => return error.FileNotFound, .PATH_NOT_FOUND => return error.FileNotFound, .ACCESS_DENIED => return error.AccessDenied, .INVALID_PARAMETER => unreachable, .INVALID_NAME => return error.InvalidName, else => |err| return unexpectedError(err), } } } pub const LoadLibraryError = error{ FileNotFound, Unexpected, }; pub fn LoadLibraryW(lpLibFileName: [*:0]const u16) LoadLibraryError!HMODULE { return kernel32.LoadLibraryW(lpLibFileName) orelse { switch (kernel32.GetLastError()) { .FILE_NOT_FOUND => return error.FileNotFound, .PATH_NOT_FOUND => return error.FileNotFound, .MOD_NOT_FOUND => return error.FileNotFound, else => |err| return unexpectedError(err), } }; } pub fn FreeLibrary(hModule: HMODULE) void { assert(kernel32.FreeLibrary(hModule) != 0); } pub fn QueryPerformanceFrequency() u64 { // "On systems that run Windows XP or later, the function will always succeed" // https://docs.microsoft.com/en-us/windows/desktop/api/profileapi/nf-profileapi-queryperformancefrequency var result: LARGE_INTEGER = undefined; assert(kernel32.QueryPerformanceFrequency(&result) != 0); // The kernel treats this integer as unsigned. return @bitCast(u64, result); } pub fn QueryPerformanceCounter() u64 { // "On systems that run Windows XP or later, the function will always succeed" // https://docs.microsoft.com/en-us/windows/desktop/api/profileapi/nf-profileapi-queryperformancecounter var result: LARGE_INTEGER = undefined; assert(kernel32.QueryPerformanceCounter(&result) != 0); // The kernel treats this integer as unsigned. return @bitCast(u64, result); } pub fn InitOnceExecuteOnce(InitOnce: *INIT_ONCE, InitFn: INIT_ONCE_FN, Parameter: ?*anyopaque, Context: ?*anyopaque) void { assert(kernel32.InitOnceExecuteOnce(InitOnce, InitFn, Parameter, Context) != 0); } pub fn HeapFree(hHeap: HANDLE, dwFlags: DWORD, lpMem: *anyopaque) void { assert(kernel32.HeapFree(hHeap, dwFlags, lpMem) != 0); } pub fn HeapDestroy(hHeap: HANDLE) void { assert(kernel32.HeapDestroy(hHeap) != 0); } pub fn LocalFree(hMem: HLOCAL) void { assert(kernel32.LocalFree(hMem) == null); } pub const GetFileInformationByHandleError = error{Unexpected}; pub fn GetFileInformationByHandle( hFile: HANDLE, ) GetFileInformationByHandleError!BY_HANDLE_FILE_INFORMATION { var info: BY_HANDLE_FILE_INFORMATION = undefined; const rc = ntdll.GetFileInformationByHandle(hFile, &info); if (rc == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } return info; } pub const SetFileTimeError = error{Unexpected}; pub fn SetFileTime( hFile: HANDLE, lpCreationTime: ?*const FILETIME, lpLastAccessTime: ?*const FILETIME, lpLastWriteTime: ?*const FILETIME, ) SetFileTimeError!void { const rc = kernel32.SetFileTime(hFile, lpCreationTime, lpLastAccessTime, lpLastWriteTime); if (rc == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub const LockFileError = error{ SystemResources, WouldBlock, } || std.os.UnexpectedError; pub fn LockFile( FileHandle: HANDLE, Event: ?HANDLE, ApcRoutine: ?*IO_APC_ROUTINE, ApcContext: ?*anyopaque, IoStatusBlock: *IO_STATUS_BLOCK, ByteOffset: *const LARGE_INTEGER, Length: *const LARGE_INTEGER, Key: ?*ULONG, FailImmediately: BOOLEAN, ExclusiveLock: BOOLEAN, ) !void { const rc = ntdll.NtLockFile( FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, ByteOffset, Length, Key, FailImmediately, ExclusiveLock, ); switch (rc) { .SUCCESS => return, .INSUFFICIENT_RESOURCES => return error.SystemResources, .LOCK_NOT_GRANTED => return error.WouldBlock, .ACCESS_VIOLATION => unreachable, // bad io_status_block pointer else => return unexpectedStatus(rc), } } pub const UnlockFileError = error{ RangeNotLocked, } || std.os.UnexpectedError; pub fn UnlockFile( FileHandle: HANDLE, IoStatusBlock: *IO_STATUS_BLOCK, ByteOffset: *const LARGE_INTEGER, Length: *const LARGE_INTEGER, Key: ?*ULONG, ) !void { const rc = ntdll.NtUnlockFile(FileHandle, IoStatusBlock, ByteOffset, Length, Key); switch (rc) { .SUCCESS => return, .RANGE_NOT_LOCKED => return error.RangeNotLocked, .ACCESS_VIOLATION => unreachable, // bad io_status_block pointer else => return unexpectedStatus(rc), } } pub fn teb() *TEB { return switch (native_arch) { .i386 => asm volatile ( \\ movl %%fs:0x18, %[ptr] : [ptr] "=r" (-> *TEB), ), .x86_64 => asm volatile ( \\ movq %%gs:0x30, %[ptr] : [ptr] "=r" (-> *TEB), ), .aarch64 => asm volatile ( \\ mov %[ptr], x18 : [ptr] "=r" (-> *TEB), ), else => @compileError("unsupported arch"), }; } pub fn peb() *PEB { return teb().ProcessEnvironmentBlock; } /// A file time is a 64-bit value that represents the number of 100-nanosecond /// intervals that have elapsed since 12:00 A.M. January 1, 1601 Coordinated /// Universal Time (UTC). /// This function returns the number of nanoseconds since the canonical epoch, /// which is the POSIX one (Jan 01, 1970 AD). pub fn fromSysTime(hns: i64) i128 { const adjusted_epoch: i128 = hns + std.time.epoch.windows * (std.time.ns_per_s / 100); return adjusted_epoch * 100; } pub fn toSysTime(ns: i128) i64 { const hns = @divFloor(ns, 100); return @intCast(i64, hns) - std.time.epoch.windows * (std.time.ns_per_s / 100); } pub fn fileTimeToNanoSeconds(ft: FILETIME) i128 { const hns = (@as(i64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime; return fromSysTime(hns); } /// Converts a number of nanoseconds since the POSIX epoch to a Windows FILETIME. pub fn nanoSecondsToFileTime(ns: i128) FILETIME { const adjusted = @bitCast(u64, toSysTime(ns)); return FILETIME{ .dwHighDateTime = @truncate(u32, adjusted >> 32), .dwLowDateTime = @truncate(u32, adjusted), }; } pub const PathSpace = struct { data: [PATH_MAX_WIDE:0]u16, len: usize, pub fn span(self: PathSpace) [:0]const u16 { return self.data[0..self.len :0]; } }; /// The error type for `removeDotDirsSanitized` pub const RemoveDotDirsError = error{TooManyParentDirs}; /// Removes '.' and '..' path components from a "sanitized relative path". /// A "sanitized path" is one where: /// 1) all forward slashes have been replaced with back slashes /// 2) all repeating back slashes have been collapsed /// 3) the path is a relative one (does not start with a back slash) pub fn removeDotDirsSanitized(comptime T: type, path: []T) RemoveDotDirsError!usize { std.debug.assert(path.len == 0 or path[0] != '\\'); var write_idx: usize = 0; var read_idx: usize = 0; while (read_idx < path.len) { if (path[read_idx] == '.') { if (read_idx + 1 == path.len) return write_idx; const after_dot = path[read_idx + 1]; if (after_dot == '\\') { read_idx += 2; continue; } if (after_dot == '.' and (read_idx + 2 == path.len or path[read_idx + 2] == '\\')) { if (write_idx == 0) return error.TooManyParentDirs; std.debug.assert(write_idx >= 2); write_idx -= 1; while (true) { write_idx -= 1; if (write_idx == 0) break; if (path[write_idx] == '\\') { write_idx += 1; break; } } if (read_idx + 2 == path.len) return write_idx; read_idx += 3; continue; } } // skip to the next path separator while (true) : (read_idx += 1) { if (read_idx == path.len) return write_idx; path[write_idx] = path[read_idx]; write_idx += 1; if (path[read_idx] == '\\') break; } read_idx += 1; } return write_idx; } /// Normalizes a Windows path with the following steps: /// 1) convert all forward slashes to back slashes /// 2) collapse duplicate back slashes /// 3) remove '.' and '..' directory parts /// Returns the length of the new path. pub fn normalizePath(comptime T: type, path: []T) RemoveDotDirsError!usize { mem.replaceScalar(T, path, '/', '\\'); const new_len = mem.collapseRepeatsLen(T, path, '\\'); const prefix_len: usize = init: { if (new_len >= 1 and path[0] == '\\') break :init 1; if (new_len >= 2 and path[1] == ':') break :init if (new_len >= 3 and path[2] == '\\') @as(usize, 3) else @as(usize, 2); break :init 0; }; return prefix_len + try removeDotDirsSanitized(T, path[prefix_len..new_len]); } /// Same as `sliceToPrefixedFileW` but accepts a pointer /// to a null-terminated path. pub fn cStrToPrefixedFileW(s: [*:0]const u8) !PathSpace { return sliceToPrefixedFileW(mem.sliceTo(s, 0)); } /// Converts the path `s` to WTF16, null-terminated. If the path is absolute, /// it will get NT-style prefix `\??\` prepended automatically. pub fn sliceToPrefixedFileW(s: []const u8) !PathSpace { // TODO https://github.com/ziglang/zig/issues/2765 var path_space: PathSpace = undefined; const prefix = "\\??\\"; const prefix_index: usize = if (mem.startsWith(u8, s, prefix)) prefix.len else 0; for (s[prefix_index..]) |byte| { switch (byte) { '*', '?', '"', '<', '>', '|' => return error.BadPathName, else => {}, } } const prefix_u16 = [_]u16{ '\\', '?', '?', '\\' }; const start_index = if (prefix_index > 0 or !std.fs.path.isAbsolute(s)) 0 else blk: { mem.copy(u16, path_space.data[0..], prefix_u16[0..]); break :blk prefix_u16.len; }; path_space.len = start_index + try std.unicode.utf8ToUtf16Le(path_space.data[start_index..], s); if (path_space.len > path_space.data.len) return error.NameTooLong; path_space.len = start_index + (normalizePath(u16, path_space.data[start_index..path_space.len]) catch |err| switch (err) { error.TooManyParentDirs => { if (!std.fs.path.isAbsolute(s)) { var temp_path: PathSpace = undefined; temp_path.len = try std.unicode.utf8ToUtf16Le(&temp_path.data, s); std.debug.assert(temp_path.len == path_space.len); temp_path.data[path_space.len] = 0; path_space.len = prefix_u16.len + try getFullPathNameW(&temp_path.data, path_space.data[prefix_u16.len..]); mem.copy(u16, &path_space.data, &prefix_u16); std.debug.assert(path_space.data[path_space.len] == 0); return path_space; } return error.BadPathName; }, }); path_space.data[path_space.len] = 0; return path_space; } fn getFullPathNameW(path: [*:0]const u16, out: []u16) !usize { const result = kernel32.GetFullPathNameW(path, @intCast(u32, out.len), std.meta.assumeSentinel(out.ptr, 0), null); if (result == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } return result; } /// Assumes an absolute path. pub fn wToPrefixedFileW(s: []const u16) !PathSpace { // TODO https://github.com/ziglang/zig/issues/2765 var path_space: PathSpace = undefined; const start_index = if (mem.startsWith(u16, s, &[_]u16{ '\\', '?' })) 0 else blk: { const prefix = [_]u16{ '\\', '?', '?', '\\' }; mem.copy(u16, path_space.data[0..], &prefix); break :blk prefix.len; }; path_space.len = start_index + s.len; if (path_space.len > path_space.data.len) return error.NameTooLong; mem.copy(u16, path_space.data[start_index..], s); // > File I/O functions in the Windows API convert "/" to "\" as part of // > converting the name to an NT-style name, except when using the "\\?\" // > prefix as detailed in the following sections. // from https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation // Because we want the larger maximum path length for absolute paths, we // convert forward slashes to backward slashes here. for (path_space.data[0..path_space.len]) |*elem| { if (elem.* == '/') { elem.* = '\\'; } } path_space.data[path_space.len] = 0; return path_space; } inline fn MAKELANGID(p: c_ushort, s: c_ushort) LANGID { return (s << 10) | p; } /// Loads a Winsock extension function in runtime specified by a GUID. pub fn loadWinsockExtensionFunction(comptime T: type, sock: ws2_32.SOCKET, guid: GUID) !T { var function: T = undefined; var num_bytes: DWORD = undefined; const rc = ws2_32.WSAIoctl( sock, ws2_32.SIO_GET_EXTENSION_FUNCTION_POINTER, @ptrCast(*const anyopaque, &guid), @sizeOf(GUID), &function, @sizeOf(T), &num_bytes, null, null, ); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAEOPNOTSUPP => error.OperationNotSupported, .WSAENOTSOCK => error.FileDescriptorNotASocket, else => |err| unexpectedWSAError(err), }; } if (num_bytes != @sizeOf(T)) { return error.ShortRead; } return function; } /// Call this when you made a windows DLL call or something that does SetLastError /// and you get an unexpected error. pub fn unexpectedError(err: Win32Error) std.os.UnexpectedError { if (std.os.unexpected_error_tracing) { // 614 is the length of the longest windows error desciption var buf_wstr: [614]WCHAR = undefined; var buf_utf8: [614]u8 = undefined; const len = kernel32.FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, err, MAKELANGID(LANG.NEUTRAL, SUBLANG.DEFAULT), &buf_wstr, buf_wstr.len, null, ); _ = std.unicode.utf16leToUtf8(&buf_utf8, buf_wstr[0..len]) catch unreachable; std.debug.print("error.Unexpected: GetLastError({}): {s}\n", .{ @enumToInt(err), buf_utf8[0..len] }); std.debug.dumpCurrentStackTrace(null); } return error.Unexpected; } pub fn unexpectedWSAError(err: ws2_32.WinsockError) std.os.UnexpectedError { return unexpectedError(@intToEnum(Win32Error, @enumToInt(err))); } /// Call this when you made a windows NtDll call /// and you get an unexpected status. pub fn unexpectedStatus(status: NTSTATUS) std.os.UnexpectedError { if (std.os.unexpected_error_tracing) { std.debug.print("error.Unexpected NTSTATUS=0x{x}\n", .{@enumToInt(status)}); std.debug.dumpCurrentStackTrace(null); } return error.Unexpected; } pub fn SetThreadDescription(hThread: HANDLE, lpThreadDescription: LPCWSTR) !void { if (kernel32.SetThreadDescription(hThread, lpThreadDescription) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub fn GetThreadDescription(hThread: HANDLE, ppszThreadDescription: *LPWSTR) !void { if (kernel32.GetThreadDescription(hThread, ppszThreadDescription) == 0) { switch (kernel32.GetLastError()) { else => |err| return unexpectedError(err), } } } pub const Win32Error = @import("windows/win32error.zig").Win32Error; pub const NTSTATUS = @import("windows/ntstatus.zig").NTSTATUS; pub const LANG = @import("windows/lang.zig"); pub const SUBLANG = @import("windows/sublang.zig"); /// The standard input device. Initially, this is the console input buffer, CONIN$. pub const STD_INPUT_HANDLE = maxInt(DWORD) - 10 + 1; /// The standard output device. Initially, this is the active console screen buffer, CONOUT$. pub const STD_OUTPUT_HANDLE = maxInt(DWORD) - 11 + 1; /// The standard error device. Initially, this is the active console screen buffer, CONOUT$. pub const STD_ERROR_HANDLE = maxInt(DWORD) - 12 + 1; pub const WINAPI: std.builtin.CallingConvention = if (native_arch == .i386) .Stdcall else .C; pub const BOOL = c_int; pub const BOOLEAN = BYTE; pub const BYTE = u8; pub const CHAR = u8; pub const UCHAR = u8; pub const FLOAT = f32; pub const HANDLE = *anyopaque; pub const HCRYPTPROV = ULONG_PTR; pub const ATOM = u16; pub const HBRUSH = *opaque {}; pub const HCURSOR = *opaque {}; pub const HICON = *opaque {}; pub const HINSTANCE = *opaque {}; pub const HMENU = *opaque {}; pub const HMODULE = *opaque {}; pub const HWND = *opaque {}; pub const HDC = *opaque {}; pub const HGLRC = *opaque {}; pub const FARPROC = *opaque {}; pub const INT = c_int; pub const LPCSTR = [*:0]const CHAR; pub const LPCVOID = *const anyopaque; pub const LPSTR = [*:0]CHAR; pub const LPVOID = *anyopaque; pub const LPWSTR = [*:0]WCHAR; pub const LPCWSTR = [*:0]const WCHAR; pub const PVOID = *anyopaque; pub const PWSTR = [*:0]WCHAR; pub const SIZE_T = usize; pub const UINT = c_uint; pub const ULONG_PTR = usize; pub const LONG_PTR = isize; pub const DWORD_PTR = ULONG_PTR; pub const WCHAR = u16; pub const WORD = u16; pub const DWORD = u32; pub const DWORD64 = u64; pub const LARGE_INTEGER = i64; pub const ULARGE_INTEGER = u64; pub const USHORT = u16; pub const SHORT = i16; pub const ULONG = u32; pub const LONG = i32; pub const ULONGLONG = u64; pub const LONGLONG = i64; pub const HLOCAL = HANDLE; pub const LANGID = c_ushort; pub const WPARAM = usize; pub const LPARAM = LONG_PTR; pub const LRESULT = LONG_PTR; pub const va_list = *opaque {}; pub const TRUE = 1; pub const FALSE = 0; pub const DEVICE_TYPE = ULONG; pub const FILE_DEVICE_BEEP: DEVICE_TYPE = 0x0001; pub const FILE_DEVICE_CD_ROM: DEVICE_TYPE = 0x0002; pub const FILE_DEVICE_CD_ROM_FILE_SYSTEM: DEVICE_TYPE = 0x0003; pub const FILE_DEVICE_CONTROLLER: DEVICE_TYPE = 0x0004; pub const FILE_DEVICE_DATALINK: DEVICE_TYPE = 0x0005; pub const FILE_DEVICE_DFS: DEVICE_TYPE = 0x0006; pub const FILE_DEVICE_DISK: DEVICE_TYPE = 0x0007; pub const FILE_DEVICE_DISK_FILE_SYSTEM: DEVICE_TYPE = 0x0008; pub const FILE_DEVICE_FILE_SYSTEM: DEVICE_TYPE = 0x0009; pub const FILE_DEVICE_INPORT_PORT: DEVICE_TYPE = 0x000a; pub const FILE_DEVICE_KEYBOARD: DEVICE_TYPE = 0x000b; pub const FILE_DEVICE_MAILSLOT: DEVICE_TYPE = 0x000c; pub const FILE_DEVICE_MIDI_IN: DEVICE_TYPE = 0x000d; pub const FILE_DEVICE_MIDI_OUT: DEVICE_TYPE = 0x000e; pub const FILE_DEVICE_MOUSE: DEVICE_TYPE = 0x000f; pub const FILE_DEVICE_MULTI_UNC_PROVIDER: DEVICE_TYPE = 0x0010; pub const FILE_DEVICE_NAMED_PIPE: DEVICE_TYPE = 0x0011; pub const FILE_DEVICE_NETWORK: DEVICE_TYPE = 0x0012; pub const FILE_DEVICE_NETWORK_BROWSER: DEVICE_TYPE = 0x0013; pub const FILE_DEVICE_NETWORK_FILE_SYSTEM: DEVICE_TYPE = 0x0014; pub const FILE_DEVICE_NULL: DEVICE_TYPE = 0x0015; pub const FILE_DEVICE_PARALLEL_PORT: DEVICE_TYPE = 0x0016; pub const FILE_DEVICE_PHYSICAL_NETCARD: DEVICE_TYPE = 0x0017; pub const FILE_DEVICE_PRINTER: DEVICE_TYPE = 0x0018; pub const FILE_DEVICE_SCANNER: DEVICE_TYPE = 0x0019; pub const FILE_DEVICE_SERIAL_MOUSE_PORT: DEVICE_TYPE = 0x001a; pub const FILE_DEVICE_SERIAL_PORT: DEVICE_TYPE = 0x001b; pub const FILE_DEVICE_SCREEN: DEVICE_TYPE = 0x001c; pub const FILE_DEVICE_SOUND: DEVICE_TYPE = 0x001d; pub const FILE_DEVICE_STREAMS: DEVICE_TYPE = 0x001e; pub const FILE_DEVICE_TAPE: DEVICE_TYPE = 0x001f; pub const FILE_DEVICE_TAPE_FILE_SYSTEM: DEVICE_TYPE = 0x0020; pub const FILE_DEVICE_TRANSPORT: DEVICE_TYPE = 0x0021; pub const FILE_DEVICE_UNKNOWN: DEVICE_TYPE = 0x0022; pub const FILE_DEVICE_VIDEO: DEVICE_TYPE = 0x0023; pub const FILE_DEVICE_VIRTUAL_DISK: DEVICE_TYPE = 0x0024; pub const FILE_DEVICE_WAVE_IN: DEVICE_TYPE = 0x0025; pub const FILE_DEVICE_WAVE_OUT: DEVICE_TYPE = 0x0026; pub const FILE_DEVICE_8042_PORT: DEVICE_TYPE = 0x0027; pub const FILE_DEVICE_NETWORK_REDIRECTOR: DEVICE_TYPE = 0x0028; pub const FILE_DEVICE_BATTERY: DEVICE_TYPE = 0x0029; pub const FILE_DEVICE_BUS_EXTENDER: DEVICE_TYPE = 0x002a; pub const FILE_DEVICE_MODEM: DEVICE_TYPE = 0x002b; pub const FILE_DEVICE_VDM: DEVICE_TYPE = 0x002c; pub const FILE_DEVICE_MASS_STORAGE: DEVICE_TYPE = 0x002d; pub const FILE_DEVICE_SMB: DEVICE_TYPE = 0x002e; pub const FILE_DEVICE_KS: DEVICE_TYPE = 0x002f; pub const FILE_DEVICE_CHANGER: DEVICE_TYPE = 0x0030; pub const FILE_DEVICE_SMARTCARD: DEVICE_TYPE = 0x0031; pub const FILE_DEVICE_ACPI: DEVICE_TYPE = 0x0032; pub const FILE_DEVICE_DVD: DEVICE_TYPE = 0x0033; pub const FILE_DEVICE_FULLSCREEN_VIDEO: DEVICE_TYPE = 0x0034; pub const FILE_DEVICE_DFS_FILE_SYSTEM: DEVICE_TYPE = 0x0035; pub const FILE_DEVICE_DFS_VOLUME: DEVICE_TYPE = 0x0036; pub const FILE_DEVICE_SERENUM: DEVICE_TYPE = 0x0037; pub const FILE_DEVICE_TERMSRV: DEVICE_TYPE = 0x0038; pub const FILE_DEVICE_KSEC: DEVICE_TYPE = 0x0039; pub const FILE_DEVICE_FIPS: DEVICE_TYPE = 0x003a; pub const FILE_DEVICE_INFINIBAND: DEVICE_TYPE = 0x003b; // TODO: missing values? pub const FILE_DEVICE_VMBUS: DEVICE_TYPE = 0x003e; pub const FILE_DEVICE_CRYPT_PROVIDER: DEVICE_TYPE = 0x003f; pub const FILE_DEVICE_WPD: DEVICE_TYPE = 0x0040; pub const FILE_DEVICE_BLUETOOTH: DEVICE_TYPE = 0x0041; pub const FILE_DEVICE_MT_COMPOSITE: DEVICE_TYPE = 0x0042; pub const FILE_DEVICE_MT_TRANSPORT: DEVICE_TYPE = 0x0043; pub const FILE_DEVICE_BIOMETRIC: DEVICE_TYPE = 0x0044; pub const FILE_DEVICE_PMI: DEVICE_TYPE = 0x0045; pub const FILE_DEVICE_EHSTOR: DEVICE_TYPE = 0x0046; pub const FILE_DEVICE_DEVAPI: DEVICE_TYPE = 0x0047; pub const FILE_DEVICE_GPIO: DEVICE_TYPE = 0x0048; pub const FILE_DEVICE_USBEX: DEVICE_TYPE = 0x0049; pub const FILE_DEVICE_CONSOLE: DEVICE_TYPE = 0x0050; pub const FILE_DEVICE_NFP: DEVICE_TYPE = 0x0051; pub const FILE_DEVICE_SYSENV: DEVICE_TYPE = 0x0052; pub const FILE_DEVICE_VIRTUAL_BLOCK: DEVICE_TYPE = 0x0053; pub const FILE_DEVICE_POINT_OF_SERVICE: DEVICE_TYPE = 0x0054; pub const FILE_DEVICE_STORAGE_REPLICATION: DEVICE_TYPE = 0x0055; pub const FILE_DEVICE_TRUST_ENV: DEVICE_TYPE = 0x0056; pub const FILE_DEVICE_UCM: DEVICE_TYPE = 0x0057; pub const FILE_DEVICE_UCMTCPCI: DEVICE_TYPE = 0x0058; pub const FILE_DEVICE_PERSISTENT_MEMORY: DEVICE_TYPE = 0x0059; pub const FILE_DEVICE_NVDIMM: DEVICE_TYPE = 0x005a; pub const FILE_DEVICE_HOLOGRAPHIC: DEVICE_TYPE = 0x005b; pub const FILE_DEVICE_SDFXHCI: DEVICE_TYPE = 0x005c; /// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/buffer-descriptions-for-i-o-control-codes pub const TransferType = enum(u2) { METHOD_BUFFERED = 0, METHOD_IN_DIRECT = 1, METHOD_OUT_DIRECT = 2, METHOD_NEITHER = 3, }; pub const FILE_ANY_ACCESS = 0; pub const FILE_READ_ACCESS = 1; pub const FILE_WRITE_ACCESS = 2; /// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/defining-i-o-control-codes pub fn CTL_CODE(deviceType: u16, function: u12, method: TransferType, access: u2) DWORD { return (@as(DWORD, deviceType) << 16) | (@as(DWORD, access) << 14) | (@as(DWORD, function) << 2) | @enumToInt(method); } pub const INVALID_HANDLE_VALUE = @intToPtr(HANDLE, maxInt(usize)); pub const INVALID_FILE_ATTRIBUTES = @as(DWORD, maxInt(DWORD)); pub const FILE_ALL_INFORMATION = extern struct { BasicInformation: FILE_BASIC_INFORMATION, StandardInformation: FILE_STANDARD_INFORMATION, InternalInformation: FILE_INTERNAL_INFORMATION, EaInformation: FILE_EA_INFORMATION, AccessInformation: FILE_ACCESS_INFORMATION, PositionInformation: FILE_POSITION_INFORMATION, ModeInformation: FILE_MODE_INFORMATION, AlignmentInformation: FILE_ALIGNMENT_INFORMATION, NameInformation: FILE_NAME_INFORMATION, }; pub const FILE_BASIC_INFORMATION = extern struct { CreationTime: LARGE_INTEGER, LastAccessTime: LARGE_INTEGER, LastWriteTime: LARGE_INTEGER, ChangeTime: LARGE_INTEGER, FileAttributes: ULONG, }; pub const FILE_STANDARD_INFORMATION = extern struct { AllocationSize: LARGE_INTEGER, EndOfFile: LARGE_INTEGER, NumberOfLinks: ULONG, DeletePending: BOOLEAN, Directory: BOOLEAN, }; pub const FILE_INTERNAL_INFORMATION = extern struct { IndexNumber: LARGE_INTEGER, }; pub const FILE_EA_INFORMATION = extern struct { EaSize: ULONG, }; pub const FILE_ACCESS_INFORMATION = extern struct { AccessFlags: ACCESS_MASK, }; pub const FILE_POSITION_INFORMATION = extern struct { CurrentByteOffset: LARGE_INTEGER, }; pub const FILE_END_OF_FILE_INFORMATION = extern struct { EndOfFile: LARGE_INTEGER, }; pub const FILE_MODE_INFORMATION = extern struct { Mode: ULONG, }; pub const FILE_ALIGNMENT_INFORMATION = extern struct { AlignmentRequirement: ULONG, }; pub const FILE_NAME_INFORMATION = extern struct { FileNameLength: ULONG, FileName: [1]WCHAR, }; pub const FILE_RENAME_INFORMATION = extern struct { ReplaceIfExists: BOOLEAN, RootDirectory: ?HANDLE, FileNameLength: ULONG, FileName: [1]WCHAR, }; pub const IO_STATUS_BLOCK = extern struct { // "DUMMYUNIONNAME" expands to "u" u: extern union { Status: NTSTATUS, Pointer: ?*anyopaque, }, Information: ULONG_PTR, }; pub const FILE_INFORMATION_CLASS = enum(c_int) { FileDirectoryInformation = 1, FileFullDirectoryInformation, FileBothDirectoryInformation, FileBasicInformation, FileStandardInformation, FileInternalInformation, FileEaInformation, FileAccessInformation, FileNameInformation, FileRenameInformation, FileLinkInformation, FileNamesInformation, FileDispositionInformation, FilePositionInformation, FileFullEaInformation, FileModeInformation, FileAlignmentInformation, FileAllInformation, FileAllocationInformation, FileEndOfFileInformation, FileAlternateNameInformation, FileStreamInformation, FilePipeInformation, FilePipeLocalInformation, FilePipeRemoteInformation, FileMailslotQueryInformation, FileMailslotSetInformation, FileCompressionInformation, FileObjectIdInformation, FileCompletionInformation, FileMoveClusterInformation, FileQuotaInformation, FileReparsePointInformation, FileNetworkOpenInformation, FileAttributeTagInformation, FileTrackingInformation, FileIdBothDirectoryInformation, FileIdFullDirectoryInformation, FileValidDataLengthInformation, FileShortNameInformation, FileIoCompletionNotificationInformation, FileIoStatusBlockRangeInformation, FileIoPriorityHintInformation, FileSfioReserveInformation, FileSfioVolumeInformation, FileHardLinkInformation, FileProcessIdsUsingFileInformation, FileNormalizedNameInformation, FileNetworkPhysicalNameInformation, FileIdGlobalTxDirectoryInformation, FileIsRemoteDeviceInformation, FileUnusedInformation, FileNumaNodeInformation, FileStandardLinkInformation, FileRemoteProtocolInformation, FileRenameInformationBypassAccessCheck, FileLinkInformationBypassAccessCheck, FileVolumeNameInformation, FileIdInformation, FileIdExtdDirectoryInformation, FileReplaceCompletionInformation, FileHardLinkFullIdInformation, FileIdExtdBothDirectoryInformation, FileDispositionInformationEx, FileRenameInformationEx, FileRenameInformationExBypassAccessCheck, FileDesiredStorageClassInformation, FileStatInformation, FileMemoryPartitionInformation, FileStatLxInformation, FileCaseSensitiveInformation, FileLinkInformationEx, FileLinkInformationExBypassAccessCheck, FileStorageReserveIdInformation, FileCaseSensitiveInformationForceAccessCheck, FileMaximumInformation, }; pub const OVERLAPPED = extern struct { Internal: ULONG_PTR, InternalHigh: ULONG_PTR, DUMMYUNIONNAME: extern union { DUMMYSTRUCTNAME: extern struct { Offset: DWORD, OffsetHigh: DWORD, }, Pointer: ?PVOID, }, hEvent: ?HANDLE, }; pub const OVERLAPPED_ENTRY = extern struct { lpCompletionKey: ULONG_PTR, lpOverlapped: *OVERLAPPED, Internal: ULONG_PTR, dwNumberOfBytesTransferred: DWORD, }; pub const MAX_PATH = 260; // TODO issue #305 pub const FILE_INFO_BY_HANDLE_CLASS = u32; pub const FileBasicInfo = 0; pub const FileStandardInfo = 1; pub const FileNameInfo = 2; pub const FileRenameInfo = 3; pub const FileDispositionInfo = 4; pub const FileAllocationInfo = 5; pub const FileEndOfFileInfo = 6; pub const FileStreamInfo = 7; pub const FileCompressionInfo = 8; pub const FileAttributeTagInfo = 9; pub const FileIdBothDirectoryInfo = 10; pub const FileIdBothDirectoryRestartInfo = 11; pub const FileIoPriorityHintInfo = 12; pub const FileRemoteProtocolInfo = 13; pub const FileFullDirectoryInfo = 14; pub const FileFullDirectoryRestartInfo = 15; pub const FileStorageInfo = 16; pub const FileAlignmentInfo = 17; pub const FileIdInfo = 18; pub const FileIdExtdDirectoryInfo = 19; pub const FileIdExtdDirectoryRestartInfo = 20; pub const BY_HANDLE_FILE_INFORMATION = extern struct { dwFileAttributes: DWORD, ftCreationTime: FILETIME, ftLastAccessTime: FILETIME, ftLastWriteTime: FILETIME, dwVolumeSerialNumber: DWORD, nFileSizeHigh: DWORD, nFileSizeLow: DWORD, nNumberOfLinks: DWORD, nFileIndexHigh: DWORD, nFileIndexLow: DWORD, }; pub const FILE_NAME_INFO = extern struct { FileNameLength: DWORD, FileName: [1]WCHAR, }; /// Return the normalized drive name. This is the default. pub const FILE_NAME_NORMALIZED = 0x0; /// Return the opened file name (not normalized). pub const FILE_NAME_OPENED = 0x8; /// Return the path with the drive letter. This is the default. pub const VOLUME_NAME_DOS = 0x0; /// Return the path with a volume GUID path instead of the drive name. pub const VOLUME_NAME_GUID = 0x1; /// Return the path with no drive information. pub const VOLUME_NAME_NONE = 0x4; /// Return the path with the volume device path. pub const VOLUME_NAME_NT = 0x2; pub const SECURITY_ATTRIBUTES = extern struct { nLength: DWORD, lpSecurityDescriptor: ?*anyopaque, bInheritHandle: BOOL, }; pub const PIPE_ACCESS_INBOUND = 0x00000001; pub const PIPE_ACCESS_OUTBOUND = 0x00000002; pub const PIPE_ACCESS_DUPLEX = 0x00000003; pub const PIPE_TYPE_BYTE = 0x00000000; pub const PIPE_TYPE_MESSAGE = 0x00000004; pub const PIPE_READMODE_BYTE = 0x00000000; pub const PIPE_READMODE_MESSAGE = 0x00000002; pub const PIPE_WAIT = 0x00000000; pub const PIPE_NOWAIT = 0x00000001; pub const GENERIC_READ = 0x80000000; pub const GENERIC_WRITE = 0x40000000; pub const GENERIC_EXECUTE = 0x20000000; pub const GENERIC_ALL = 0x10000000; pub const FILE_SHARE_DELETE = 0x00000004; pub const FILE_SHARE_READ = 0x00000001; pub const FILE_SHARE_WRITE = 0x00000002; pub const DELETE = 0x00010000; pub const READ_CONTROL = 0x00020000; pub const WRITE_DAC = 0x00040000; pub const WRITE_OWNER = 0x00080000; pub const SYNCHRONIZE = 0x00100000; pub const STANDARD_RIGHTS_READ = READ_CONTROL; pub const STANDARD_RIGHTS_WRITE = READ_CONTROL; pub const STANDARD_RIGHTS_EXECUTE = READ_CONTROL; pub const STANDARD_RIGHTS_REQUIRED = DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER; // disposition for NtCreateFile pub const FILE_SUPERSEDE = 0; pub const FILE_OPEN = 1; pub const FILE_CREATE = 2; pub const FILE_OPEN_IF = 3; pub const FILE_OVERWRITE = 4; pub const FILE_OVERWRITE_IF = 5; pub const FILE_MAXIMUM_DISPOSITION = 5; // flags for NtCreateFile and NtOpenFile pub const FILE_READ_DATA = 0x00000001; pub const FILE_LIST_DIRECTORY = 0x00000001; pub const FILE_WRITE_DATA = 0x00000002; pub const FILE_ADD_FILE = 0x00000002; pub const FILE_APPEND_DATA = 0x00000004; pub const FILE_ADD_SUBDIRECTORY = 0x00000004; pub const FILE_CREATE_PIPE_INSTANCE = 0x00000004; pub const FILE_READ_EA = 0x00000008; pub const FILE_WRITE_EA = 0x00000010; pub const FILE_EXECUTE = 0x00000020; pub const FILE_TRAVERSE = 0x00000020; pub const FILE_DELETE_CHILD = 0x00000040; pub const FILE_READ_ATTRIBUTES = 0x00000080; pub const FILE_WRITE_ATTRIBUTES = 0x00000100; pub const FILE_DIRECTORY_FILE = 0x00000001; pub const FILE_WRITE_THROUGH = 0x00000002; pub const FILE_SEQUENTIAL_ONLY = 0x00000004; pub const FILE_NO_INTERMEDIATE_BUFFERING = 0x00000008; pub const FILE_SYNCHRONOUS_IO_ALERT = 0x00000010; pub const FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020; pub const FILE_NON_DIRECTORY_FILE = 0x00000040; pub const FILE_CREATE_TREE_CONNECTION = 0x00000080; pub const FILE_COMPLETE_IF_OPLOCKED = 0x00000100; pub const FILE_NO_EA_KNOWLEDGE = 0x00000200; pub const FILE_OPEN_FOR_RECOVERY = 0x00000400; pub const FILE_RANDOM_ACCESS = 0x00000800; pub const FILE_DELETE_ON_CLOSE = 0x00001000; pub const FILE_OPEN_BY_FILE_ID = 0x00002000; pub const FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000; pub const FILE_NO_COMPRESSION = 0x00008000; pub const FILE_RESERVE_OPFILTER = 0x00100000; pub const FILE_OPEN_REPARSE_POINT = 0x00200000; pub const FILE_OPEN_OFFLINE_FILE = 0x00400000; pub const FILE_OPEN_FOR_FREE_SPACE_QUERY = 0x00800000; pub const CREATE_ALWAYS = 2; pub const CREATE_NEW = 1; pub const OPEN_ALWAYS = 4; pub const OPEN_EXISTING = 3; pub const TRUNCATE_EXISTING = 5; pub const FILE_ATTRIBUTE_ARCHIVE = 0x20; pub const FILE_ATTRIBUTE_COMPRESSED = 0x800; pub const FILE_ATTRIBUTE_DEVICE = 0x40; pub const FILE_ATTRIBUTE_DIRECTORY = 0x10; pub const FILE_ATTRIBUTE_ENCRYPTED = 0x4000; pub const FILE_ATTRIBUTE_HIDDEN = 0x2; pub const FILE_ATTRIBUTE_INTEGRITY_STREAM = 0x8000; pub const FILE_ATTRIBUTE_NORMAL = 0x80; pub const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x2000; pub const FILE_ATTRIBUTE_NO_SCRUB_DATA = 0x20000; pub const FILE_ATTRIBUTE_OFFLINE = 0x1000; pub const FILE_ATTRIBUTE_READONLY = 0x1; pub const FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x400000; pub const FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x40000; pub const FILE_ATTRIBUTE_REPARSE_POINT = 0x400; pub const FILE_ATTRIBUTE_SPARSE_FILE = 0x200; pub const FILE_ATTRIBUTE_SYSTEM = 0x4; pub const FILE_ATTRIBUTE_TEMPORARY = 0x100; pub const FILE_ATTRIBUTE_VIRTUAL = 0x10000; // flags for CreateEvent pub const CREATE_EVENT_INITIAL_SET = 0x00000002; pub const CREATE_EVENT_MANUAL_RESET = 0x00000001; pub const EVENT_ALL_ACCESS = 0x1F0003; pub const EVENT_MODIFY_STATE = 0x0002; pub const PROCESS_INFORMATION = extern struct { hProcess: HANDLE, hThread: HANDLE, dwProcessId: DWORD, dwThreadId: DWORD, }; pub const STARTUPINFOW = extern struct { cb: DWORD, lpReserved: ?LPWSTR, lpDesktop: ?LPWSTR, lpTitle: ?LPWSTR, dwX: DWORD, dwY: DWORD, dwXSize: DWORD, dwYSize: DWORD, dwXCountChars: DWORD, dwYCountChars: DWORD, dwFillAttribute: DWORD, dwFlags: DWORD, wShowWindow: WORD, cbReserved2: WORD, lpReserved2: ?*BYTE, hStdInput: ?HANDLE, hStdOutput: ?HANDLE, hStdError: ?HANDLE, }; pub const STARTF_FORCEONFEEDBACK = 0x00000040; pub const STARTF_FORCEOFFFEEDBACK = 0x00000080; pub const STARTF_PREVENTPINNING = 0x00002000; pub const STARTF_RUNFULLSCREEN = 0x00000020; pub const STARTF_TITLEISAPPID = 0x00001000; pub const STARTF_TITLEISLINKNAME = 0x00000800; pub const STARTF_UNTRUSTEDSOURCE = 0x00008000; pub const STARTF_USECOUNTCHARS = 0x00000008; pub const STARTF_USEFILLATTRIBUTE = 0x00000010; pub const STARTF_USEHOTKEY = 0x00000200; pub const STARTF_USEPOSITION = 0x00000004; pub const STARTF_USESHOWWINDOW = 0x00000001; pub const STARTF_USESIZE = 0x00000002; pub const STARTF_USESTDHANDLES = 0x00000100; pub const INFINITE = 4294967295; pub const MAXIMUM_WAIT_OBJECTS = 64; pub const WAIT_ABANDONED = 0x00000080; pub const WAIT_ABANDONED_0 = WAIT_ABANDONED + 0; pub const WAIT_OBJECT_0 = 0x00000000; pub const WAIT_TIMEOUT = 0x00000102; pub const WAIT_FAILED = 0xFFFFFFFF; pub const HANDLE_FLAG_INHERIT = 0x00000001; pub const HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x00000002; pub const MOVEFILE_COPY_ALLOWED = 2; pub const MOVEFILE_CREATE_HARDLINK = 16; pub const MOVEFILE_DELAY_UNTIL_REBOOT = 4; pub const MOVEFILE_FAIL_IF_NOT_TRACKABLE = 32; pub const MOVEFILE_REPLACE_EXISTING = 1; pub const MOVEFILE_WRITE_THROUGH = 8; pub const FILE_BEGIN = 0; pub const FILE_CURRENT = 1; pub const FILE_END = 2; pub const HEAP_CREATE_ENABLE_EXECUTE = 0x00040000; pub const HEAP_REALLOC_IN_PLACE_ONLY = 0x00000010; pub const HEAP_GENERATE_EXCEPTIONS = 0x00000004; pub const HEAP_NO_SERIALIZE = 0x00000001; // AllocationType values pub const MEM_COMMIT = 0x1000; pub const MEM_RESERVE = 0x2000; pub const MEM_RESET = 0x80000; pub const MEM_RESET_UNDO = 0x1000000; pub const MEM_LARGE_PAGES = 0x20000000; pub const MEM_PHYSICAL = 0x400000; pub const MEM_TOP_DOWN = 0x100000; pub const MEM_WRITE_WATCH = 0x200000; // Protect values pub const PAGE_EXECUTE = 0x10; pub const PAGE_EXECUTE_READ = 0x20; pub const PAGE_EXECUTE_READWRITE = 0x40; pub const PAGE_EXECUTE_WRITECOPY = 0x80; pub const PAGE_NOACCESS = 0x01; pub const PAGE_READONLY = 0x02; pub const PAGE_READWRITE = 0x04; pub const PAGE_WRITECOPY = 0x08; pub const PAGE_TARGETS_INVALID = 0x40000000; pub const PAGE_TARGETS_NO_UPDATE = 0x40000000; // Same as PAGE_TARGETS_INVALID pub const PAGE_GUARD = 0x100; pub const PAGE_NOCACHE = 0x200; pub const PAGE_WRITECOMBINE = 0x400; // FreeType values pub const MEM_COALESCE_PLACEHOLDERS = 0x1; pub const MEM_RESERVE_PLACEHOLDERS = 0x2; pub const MEM_DECOMMIT = 0x4000; pub const MEM_RELEASE = 0x8000; pub const PTHREAD_START_ROUTINE = fn (LPVOID) callconv(.C) DWORD; pub const LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE; pub const WIN32_FIND_DATAW = extern struct { dwFileAttributes: DWORD, ftCreationTime: FILETIME, ftLastAccessTime: FILETIME, ftLastWriteTime: FILETIME, nFileSizeHigh: DWORD, nFileSizeLow: DWORD, dwReserved0: DWORD, dwReserved1: DWORD, cFileName: [260]u16, cAlternateFileName: [14]u16, }; pub const FILETIME = extern struct { dwLowDateTime: DWORD, dwHighDateTime: DWORD, }; pub const SYSTEM_INFO = extern struct { anon1: extern union { dwOemId: DWORD, anon2: extern struct { wProcessorArchitecture: WORD, wReserved: WORD, }, }, dwPageSize: DWORD, lpMinimumApplicationAddress: LPVOID, lpMaximumApplicationAddress: LPVOID, dwActiveProcessorMask: DWORD_PTR, dwNumberOfProcessors: DWORD, dwProcessorType: DWORD, dwAllocationGranularity: DWORD, wProcessorLevel: WORD, wProcessorRevision: WORD, }; pub const HRESULT = c_long; pub const KNOWNFOLDERID = GUID; pub const GUID = extern struct { Data1: c_ulong, Data2: c_ushort, Data3: c_ushort, Data4: [8]u8, pub fn parse(str: []const u8) GUID { var guid: GUID = undefined; var index: usize = 0; assert(str[index] == '{'); index += 1; guid.Data1 = std.fmt.parseUnsigned(c_ulong, str[index .. index + 8], 16) catch unreachable; index += 8; assert(str[index] == '-'); index += 1; guid.Data2 = std.fmt.parseUnsigned(c_ushort, str[index .. index + 4], 16) catch unreachable; index += 4; assert(str[index] == '-'); index += 1; guid.Data3 = std.fmt.parseUnsigned(c_ushort, str[index .. index + 4], 16) catch unreachable; index += 4; assert(str[index] == '-'); index += 1; guid.Data4[0] = std.fmt.parseUnsigned(u8, str[index .. index + 2], 16) catch unreachable; index += 2; guid.Data4[1] = std.fmt.parseUnsigned(u8, str[index .. index + 2], 16) catch unreachable; index += 2; assert(str[index] == '-'); index += 1; var i: usize = 2; while (i < guid.Data4.len) : (i += 1) { guid.Data4[i] = std.fmt.parseUnsigned(u8, str[index .. index + 2], 16) catch unreachable; index += 2; } assert(str[index] == '}'); index += 1; return guid; } }; pub const FOLDERID_LocalAppData = GUID.parse("{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}"); pub const KF_FLAG_DEFAULT = 0; pub const KF_FLAG_NO_APPCONTAINER_REDIRECTION = 65536; pub const KF_FLAG_CREATE = 32768; pub const KF_FLAG_DONT_VERIFY = 16384; pub const KF_FLAG_DONT_UNEXPAND = 8192; pub const KF_FLAG_NO_ALIAS = 4096; pub const KF_FLAG_INIT = 2048; pub const KF_FLAG_DEFAULT_PATH = 1024; pub const KF_FLAG_NOT_PARENT_RELATIVE = 512; pub const KF_FLAG_SIMPLE_IDLIST = 256; pub const KF_FLAG_ALIAS_ONLY = -2147483648; pub const S_OK = 0; pub const E_NOTIMPL = @bitCast(c_long, @as(c_ulong, 0x80004001)); pub const E_NOINTERFACE = @bitCast(c_long, @as(c_ulong, 0x80004002)); pub const E_POINTER = @bitCast(c_long, @as(c_ulong, 0x80004003)); pub const E_ABORT = @bitCast(c_long, @as(c_ulong, 0x80004004)); pub const E_FAIL = @bitCast(c_long, @as(c_ulong, 0x80004005)); pub const E_UNEXPECTED = @bitCast(c_long, @as(c_ulong, 0x8000FFFF)); pub const E_ACCESSDENIED = @bitCast(c_long, @as(c_ulong, 0x80070005)); pub const E_HANDLE = @bitCast(c_long, @as(c_ulong, 0x80070006)); pub const E_OUTOFMEMORY = @bitCast(c_long, @as(c_ulong, 0x8007000E)); pub const E_INVALIDARG = @bitCast(c_long, @as(c_ulong, 0x80070057)); pub const FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; pub const FILE_FLAG_DELETE_ON_CLOSE = 0x04000000; pub const FILE_FLAG_NO_BUFFERING = 0x20000000; pub const FILE_FLAG_OPEN_NO_RECALL = 0x00100000; pub const FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000; pub const FILE_FLAG_OVERLAPPED = 0x40000000; pub const FILE_FLAG_POSIX_SEMANTICS = 0x0100000; pub const FILE_FLAG_RANDOM_ACCESS = 0x10000000; pub const FILE_FLAG_SESSION_AWARE = 0x00800000; pub const FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000; pub const FILE_FLAG_WRITE_THROUGH = 0x80000000; pub const RECT = extern struct { left: LONG, top: LONG, right: LONG, bottom: LONG, }; pub const SMALL_RECT = extern struct { Left: SHORT, Top: SHORT, Right: SHORT, Bottom: SHORT, }; pub const POINT = extern struct { x: LONG, y: LONG, }; pub const COORD = extern struct { X: SHORT, Y: SHORT, }; pub const CREATE_UNICODE_ENVIRONMENT = 1024; pub const TLS_OUT_OF_INDEXES = 4294967295; pub const IMAGE_TLS_DIRECTORY = extern struct { StartAddressOfRawData: usize, EndAddressOfRawData: usize, AddressOfIndex: usize, AddressOfCallBacks: usize, SizeOfZeroFill: u32, Characteristics: u32, }; pub const IMAGE_TLS_DIRECTORY64 = IMAGE_TLS_DIRECTORY; pub const IMAGE_TLS_DIRECTORY32 = IMAGE_TLS_DIRECTORY; pub const PIMAGE_TLS_CALLBACK = ?fn (PVOID, DWORD, PVOID) callconv(.C) void; pub const PROV_RSA_FULL = 1; pub const REGSAM = ACCESS_MASK; pub const ACCESS_MASK = DWORD; pub const HKEY = *HKEY__; pub const HKEY__ = extern struct { unused: c_int, }; pub const LSTATUS = LONG; pub const FILE_NOTIFY_INFORMATION = extern struct { NextEntryOffset: DWORD, Action: DWORD, FileNameLength: DWORD, // Flexible array member // FileName: [1]WCHAR, }; pub const FILE_ACTION_ADDED = 0x00000001; pub const FILE_ACTION_REMOVED = 0x00000002; pub const FILE_ACTION_MODIFIED = 0x00000003; pub const FILE_ACTION_RENAMED_OLD_NAME = 0x00000004; pub const FILE_ACTION_RENAMED_NEW_NAME = 0x00000005; pub const LPOVERLAPPED_COMPLETION_ROUTINE = ?fn (DWORD, DWORD, *OVERLAPPED) callconv(.C) void; pub const FILE_NOTIFY_CHANGE_CREATION = 64; pub const FILE_NOTIFY_CHANGE_SIZE = 8; pub const FILE_NOTIFY_CHANGE_SECURITY = 256; pub const FILE_NOTIFY_CHANGE_LAST_ACCESS = 32; pub const FILE_NOTIFY_CHANGE_LAST_WRITE = 16; pub const FILE_NOTIFY_CHANGE_DIR_NAME = 2; pub const FILE_NOTIFY_CHANGE_FILE_NAME = 1; pub const FILE_NOTIFY_CHANGE_ATTRIBUTES = 4; pub const CONSOLE_SCREEN_BUFFER_INFO = extern struct { dwSize: COORD, dwCursorPosition: COORD, wAttributes: WORD, srWindow: SMALL_RECT, dwMaximumWindowSize: COORD, }; pub const FOREGROUND_BLUE = 1; pub const FOREGROUND_GREEN = 2; pub const FOREGROUND_RED = 4; pub const FOREGROUND_INTENSITY = 8; pub const LIST_ENTRY = extern struct { Flink: *LIST_ENTRY, Blink: *LIST_ENTRY, }; pub const RTL_CRITICAL_SECTION_DEBUG = extern struct { Type: WORD, CreatorBackTraceIndex: WORD, CriticalSection: *RTL_CRITICAL_SECTION, ProcessLocksList: LIST_ENTRY, EntryCount: DWORD, ContentionCount: DWORD, Flags: DWORD, CreatorBackTraceIndexHigh: WORD, SpareWORD: WORD, }; pub const RTL_CRITICAL_SECTION = extern struct { DebugInfo: *RTL_CRITICAL_SECTION_DEBUG, LockCount: LONG, RecursionCount: LONG, OwningThread: HANDLE, LockSemaphore: HANDLE, SpinCount: ULONG_PTR, }; pub const CRITICAL_SECTION = RTL_CRITICAL_SECTION; pub const INIT_ONCE = RTL_RUN_ONCE; pub const INIT_ONCE_STATIC_INIT = RTL_RUN_ONCE_INIT; pub const INIT_ONCE_FN = fn (InitOnce: *INIT_ONCE, Parameter: ?*anyopaque, Context: ?*anyopaque) callconv(.C) BOOL; pub const RTL_RUN_ONCE = extern struct { Ptr: ?*anyopaque, }; pub const RTL_RUN_ONCE_INIT = RTL_RUN_ONCE{ .Ptr = null }; pub const COINIT_APARTMENTTHREADED = COINIT.COINIT_APARTMENTTHREADED; pub const COINIT_MULTITHREADED = COINIT.COINIT_MULTITHREADED; pub const COINIT_DISABLE_OLE1DDE = COINIT.COINIT_DISABLE_OLE1DDE; pub const COINIT_SPEED_OVER_MEMORY = COINIT.COINIT_SPEED_OVER_MEMORY; pub const COINIT = enum(c_int) { COINIT_APARTMENTTHREADED = 2, COINIT_MULTITHREADED = 0, COINIT_DISABLE_OLE1DDE = 4, COINIT_SPEED_OVER_MEMORY = 8, }; /// > The maximum path of 32,767 characters is approximate, because the "\\?\" /// > prefix may be expanded to a longer string by the system at run time, and /// > this expansion applies to the total length. /// from https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation pub const PATH_MAX_WIDE = 32767; pub const FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; pub const FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; pub const FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; pub const FORMAT_MESSAGE_FROM_STRING = 0x00000400; pub const FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; pub const FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; pub const FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF; pub const EXCEPTION_DATATYPE_MISALIGNMENT = 0x80000002; pub const EXCEPTION_ACCESS_VIOLATION = 0xc0000005; pub const EXCEPTION_ILLEGAL_INSTRUCTION = 0xc000001d; pub const EXCEPTION_STACK_OVERFLOW = 0xc00000fd; pub const EXCEPTION_CONTINUE_SEARCH = 0; pub const EXCEPTION_RECORD = extern struct { ExceptionCode: u32, ExceptionFlags: u32, ExceptionRecord: *EXCEPTION_RECORD, ExceptionAddress: *anyopaque, NumberParameters: u32, ExceptionInformation: [15]usize, }; pub usingnamespace switch (native_arch) { .i386 => struct { pub const FLOATING_SAVE_AREA = extern struct { ControlWord: DWORD, StatusWord: DWORD, TagWord: DWORD, ErrorOffset: DWORD, ErrorSelector: DWORD, DataOffset: DWORD, DataSelector: DWORD, RegisterArea: [80]BYTE, Cr0NpxState: DWORD, }; pub const CONTEXT = extern struct { ContextFlags: DWORD, Dr0: DWORD, Dr1: DWORD, Dr2: DWORD, Dr3: DWORD, Dr6: DWORD, Dr7: DWORD, FloatSave: FLOATING_SAVE_AREA, SegGs: DWORD, SegFs: DWORD, SegEs: DWORD, SegDs: DWORD, Edi: DWORD, Esi: DWORD, Ebx: DWORD, Edx: DWORD, Ecx: DWORD, Eax: DWORD, Ebp: DWORD, Eip: DWORD, SegCs: DWORD, EFlags: DWORD, Esp: DWORD, SegSs: DWORD, ExtendedRegisters: [512]BYTE, pub fn getRegs(ctx: *const CONTEXT) struct { bp: usize, ip: usize } { return .{ .bp = ctx.Ebp, .ip = ctx.Eip }; } }; }, .x86_64 => struct { pub const M128A = extern struct { Low: ULONGLONG, High: LONGLONG, }; pub const XMM_SAVE_AREA32 = extern struct { ControlWord: WORD, StatusWord: WORD, TagWord: BYTE, Reserved1: BYTE, ErrorOpcode: WORD, ErrorOffset: DWORD, ErrorSelector: WORD, Reserved2: WORD, DataOffset: DWORD, DataSelector: WORD, Reserved3: WORD, MxCsr: DWORD, MxCsr_Mask: DWORD, FloatRegisters: [8]M128A, XmmRegisters: [16]M128A, Reserved4: [96]BYTE, }; pub const CONTEXT = extern struct { P1Home: DWORD64, P2Home: DWORD64, P3Home: DWORD64, P4Home: DWORD64, P5Home: DWORD64, P6Home: DWORD64, ContextFlags: DWORD, MxCsr: DWORD, SegCs: WORD, SegDs: WORD, SegEs: WORD, SegFs: WORD, SegGs: WORD, SegSs: WORD, EFlags: DWORD, Dr0: DWORD64, Dr1: DWORD64, Dr2: DWORD64, Dr3: DWORD64, Dr6: DWORD64, Dr7: DWORD64, Rax: DWORD64, Rcx: DWORD64, Rdx: DWORD64, Rbx: DWORD64, Rsp: DWORD64, Rbp: DWORD64, Rsi: DWORD64, Rdi: DWORD64, R8: DWORD64, R9: DWORD64, R10: DWORD64, R11: DWORD64, R12: DWORD64, R13: DWORD64, R14: DWORD64, R15: DWORD64, Rip: DWORD64, DUMMYUNIONNAME: extern union { FltSave: XMM_SAVE_AREA32, FloatSave: XMM_SAVE_AREA32, DUMMYSTRUCTNAME: extern struct { Header: [2]M128A, Legacy: [8]M128A, Xmm0: M128A, Xmm1: M128A, Xmm2: M128A, Xmm3: M128A, Xmm4: M128A, Xmm5: M128A, Xmm6: M128A, Xmm7: M128A, Xmm8: M128A, Xmm9: M128A, Xmm10: M128A, Xmm11: M128A, Xmm12: M128A, Xmm13: M128A, Xmm14: M128A, Xmm15: M128A, }, }, VectorRegister: [26]M128A, VectorControl: DWORD64, DebugControl: DWORD64, LastBranchToRip: DWORD64, LastBranchFromRip: DWORD64, LastExceptionToRip: DWORD64, LastExceptionFromRip: DWORD64, pub fn getRegs(ctx: *const CONTEXT) struct { bp: usize, ip: usize } { return .{ .bp = ctx.Rbp, .ip = ctx.Rip }; } }; }, .aarch64 => struct { pub const NEON128 = extern union { DUMMYSTRUCTNAME: extern struct { Low: ULONGLONG, High: LONGLONG, }, D: [2]f64, S: [4]f32, H: [8]WORD, B: [16]BYTE, }; pub const CONTEXT = extern struct { ContextFlags: ULONG, Cpsr: ULONG, DUMMYUNIONNAME: extern union { DUMMYSTRUCTNAME: extern struct { X0: DWORD64, X1: DWORD64, X2: DWORD64, X3: DWORD64, X4: DWORD64, X5: DWORD64, X6: DWORD64, X7: DWORD64, X8: DWORD64, X9: DWORD64, X10: DWORD64, X11: DWORD64, X12: DWORD64, X13: DWORD64, X14: DWORD64, X15: DWORD64, X16: DWORD64, X17: DWORD64, X18: DWORD64, X19: DWORD64, X20: DWORD64, X21: DWORD64, X22: DWORD64, X23: DWORD64, X24: DWORD64, X25: DWORD64, X26: DWORD64, X27: DWORD64, X28: DWORD64, Fp: DWORD64, Lr: DWORD64, }, X: [31]DWORD64, }, Sp: DWORD64, Pc: DWORD64, V: [32]NEON128, Fpcr: DWORD, Fpsr: DWORD, Bcr: [8]DWORD, Bvr: [8]DWORD64, Wcr: [2]DWORD, Wvr: [2]DWORD64, pub fn getRegs(ctx: *const CONTEXT) struct { bp: usize, ip: usize } { return .{ .bp = ctx.DUMMYUNIONNAME.DUMMYSTRUCTNAME.Fp, .ip = ctx.Pc, }; } }; }, else => struct {}, }; pub const EXCEPTION_POINTERS = extern struct { ExceptionRecord: *EXCEPTION_RECORD, ContextRecord: *std.os.windows.CONTEXT, }; pub const VECTORED_EXCEPTION_HANDLER = fn (ExceptionInfo: *EXCEPTION_POINTERS) callconv(WINAPI) c_long; pub const OBJECT_ATTRIBUTES = extern struct { Length: ULONG, RootDirectory: ?HANDLE, ObjectName: *UNICODE_STRING, Attributes: ULONG, SecurityDescriptor: ?*anyopaque, SecurityQualityOfService: ?*anyopaque, }; pub const OBJ_INHERIT = 0x00000002; pub const OBJ_PERMANENT = 0x00000010; pub const OBJ_EXCLUSIVE = 0x00000020; pub const OBJ_CASE_INSENSITIVE = 0x00000040; pub const OBJ_OPENIF = 0x00000080; pub const OBJ_OPENLINK = 0x00000100; pub const OBJ_KERNEL_HANDLE = 0x00000200; pub const OBJ_VALID_ATTRIBUTES = 0x000003F2; pub const UNICODE_STRING = extern struct { Length: c_ushort, MaximumLength: c_ushort, Buffer: [*]WCHAR, }; pub const ACTIVATION_CONTEXT_DATA = opaque {}; pub const ASSEMBLY_STORAGE_MAP = opaque {}; pub const FLS_CALLBACK_INFO = opaque {}; pub const RTL_BITMAP = opaque {}; pub const KAFFINITY = usize; pub const TEB = extern struct { Reserved1: [12]PVOID, ProcessEnvironmentBlock: *PEB, Reserved2: [399]PVOID, Reserved3: [1952]u8, TlsSlots: [64]PVOID, Reserved4: [8]u8, Reserved5: [26]PVOID, ReservedForOle: PVOID, Reserved6: [4]PVOID, TlsExpansionSlots: PVOID, }; /// Process Environment Block /// Microsoft documentation of this is incomplete, the fields here are taken from various resources including: /// - https://github.com/wine-mirror/wine/blob/1aff1e6a370ee8c0213a0fd4b220d121da8527aa/include/winternl.h#L269 /// - https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb/index.htm pub const PEB = extern struct { // Versions: All InheritedAddressSpace: BOOLEAN, // Versions: 3.51+ ReadImageFileExecOptions: BOOLEAN, BeingDebugged: BOOLEAN, // Versions: 5.2+ (previously was padding) BitField: UCHAR, // Versions: all Mutant: HANDLE, ImageBaseAddress: HMODULE, Ldr: *PEB_LDR_DATA, ProcessParameters: *RTL_USER_PROCESS_PARAMETERS, SubSystemData: PVOID, ProcessHeap: HANDLE, // Versions: 5.1+ FastPebLock: *RTL_CRITICAL_SECTION, // Versions: 5.2+ AtlThunkSListPtr: PVOID, IFEOKey: PVOID, // Versions: 6.0+ /// https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb/crossprocessflags.htm CrossProcessFlags: ULONG, // Versions: 6.0+ union1: extern union { KernelCallbackTable: PVOID, UserSharedInfoPtr: PVOID, }, // Versions: 5.1+ SystemReserved: ULONG, // Versions: 5.1, (not 5.2, not 6.0), 6.1+ AtlThunkSListPtr32: ULONG, // Versions: 6.1+ ApiSetMap: PVOID, // Versions: all TlsExpansionCounter: ULONG, // note: there is padding here on 64 bit TlsBitmap: *RTL_BITMAP, TlsBitmapBits: [2]ULONG, ReadOnlySharedMemoryBase: PVOID, // Versions: 1703+ SharedData: PVOID, // Versions: all ReadOnlyStaticServerData: *PVOID, AnsiCodePageData: PVOID, OemCodePageData: PVOID, UnicodeCaseTableData: PVOID, // Versions: 3.51+ NumberOfProcessors: ULONG, NtGlobalFlag: ULONG, // Versions: all CriticalSectionTimeout: LARGE_INTEGER, // End of Original PEB size // Fields appended in 3.51: HeapSegmentReserve: ULONG_PTR, HeapSegmentCommit: ULONG_PTR, HeapDeCommitTotalFreeThreshold: ULONG_PTR, HeapDeCommitFreeBlockThreshold: ULONG_PTR, NumberOfHeaps: ULONG, MaximumNumberOfHeaps: ULONG, ProcessHeaps: *PVOID, // Fields appended in 4.0: GdiSharedHandleTable: PVOID, ProcessStarterHelper: PVOID, GdiDCAttributeList: ULONG, // note: there is padding here on 64 bit LoaderLock: *RTL_CRITICAL_SECTION, OSMajorVersion: ULONG, OSMinorVersion: ULONG, OSBuildNumber: USHORT, OSCSDVersion: USHORT, OSPlatformId: ULONG, ImageSubSystem: ULONG, ImageSubSystemMajorVersion: ULONG, ImageSubSystemMinorVersion: ULONG, // note: there is padding here on 64 bit ActiveProcessAffinityMask: KAFFINITY, GdiHandleBuffer: [ switch (@sizeOf(usize)) { 4 => 0x22, 8 => 0x3C, else => unreachable, } ]ULONG, // Fields appended in 5.0 (Windows 2000): PostProcessInitRoutine: PVOID, TlsExpansionBitmap: *RTL_BITMAP, TlsExpansionBitmapBits: [32]ULONG, SessionId: ULONG, // note: there is padding here on 64 bit // Versions: 5.1+ AppCompatFlags: ULARGE_INTEGER, AppCompatFlagsUser: ULARGE_INTEGER, ShimData: PVOID, // Versions: 5.0+ AppCompatInfo: PVOID, CSDVersion: UNICODE_STRING, // Fields appended in 5.1 (Windows XP): ActivationContextData: *const ACTIVATION_CONTEXT_DATA, ProcessAssemblyStorageMap: *ASSEMBLY_STORAGE_MAP, SystemDefaultActivationData: *const ACTIVATION_CONTEXT_DATA, SystemAssemblyStorageMap: *ASSEMBLY_STORAGE_MAP, MinimumStackCommit: ULONG_PTR, // Fields appended in 5.2 (Windows Server 2003): FlsCallback: *FLS_CALLBACK_INFO, FlsListHead: LIST_ENTRY, FlsBitmap: *RTL_BITMAP, FlsBitmapBits: [4]ULONG, FlsHighIndex: ULONG, // Fields appended in 6.0 (Windows Vista): WerRegistrationData: PVOID, WerShipAssertPtr: PVOID, // Fields appended in 6.1 (Windows 7): pUnused: PVOID, // previously pContextData pImageHeaderHash: PVOID, /// TODO: https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb/tracingflags.htm TracingFlags: ULONG, // Fields appended in 6.2 (Windows 8): CsrServerReadOnlySharedMemoryBase: ULONGLONG, // Fields appended in 1511: TppWorkerpListLock: ULONG, TppWorkerpList: LIST_ENTRY, WaitOnAddressHashTable: [0x80]PVOID, // Fields appended in 1709: TelemetryCoverageHeader: PVOID, CloudFileFlags: ULONG, }; /// The `PEB_LDR_DATA` structure is the main record of what modules are loaded in a process. /// It is essentially the head of three double-linked lists of `LDR_DATA_TABLE_ENTRY` structures which each represent one loaded module. /// /// Microsoft documentation of this is incomplete, the fields here are taken from various resources including: /// - https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb_ldr_data.htm pub const PEB_LDR_DATA = extern struct { // Versions: 3.51 and higher /// The size in bytes of the structure Length: ULONG, /// TRUE if the structure is prepared. Initialized: BOOLEAN, SsHandle: PVOID, InLoadOrderModuleList: LIST_ENTRY, InMemoryOrderModuleList: LIST_ENTRY, InInitializationOrderModuleList: LIST_ENTRY, // Versions: 5.1 and higher /// No known use of this field is known in Windows 8 and higher. EntryInProgress: PVOID, // Versions: 6.0 from Windows Vista SP1, and higher ShutdownInProgress: BOOLEAN, /// Though ShutdownThreadId is declared as a HANDLE, /// it is indeed the thread ID as suggested by its name. /// It is picked up from the UniqueThread member of the CLIENT_ID in the /// TEB of the thread that asks to terminate the process. ShutdownThreadId: HANDLE, }; pub const RTL_USER_PROCESS_PARAMETERS = extern struct { AllocationSize: ULONG, Size: ULONG, Flags: ULONG, DebugFlags: ULONG, ConsoleHandle: HANDLE, ConsoleFlags: ULONG, hStdInput: HANDLE, hStdOutput: HANDLE, hStdError: HANDLE, CurrentDirectory: CURDIR, DllPath: UNICODE_STRING, ImagePathName: UNICODE_STRING, CommandLine: UNICODE_STRING, Environment: [*:0]WCHAR, dwX: ULONG, dwY: ULONG, dwXSize: ULONG, dwYSize: ULONG, dwXCountChars: ULONG, dwYCountChars: ULONG, dwFillAttribute: ULONG, dwFlags: ULONG, dwShowWindow: ULONG, WindowTitle: UNICODE_STRING, Desktop: UNICODE_STRING, ShellInfo: UNICODE_STRING, RuntimeInfo: UNICODE_STRING, DLCurrentDirectory: [0x20]RTL_DRIVE_LETTER_CURDIR, }; pub const RTL_DRIVE_LETTER_CURDIR = extern struct { Flags: c_ushort, Length: c_ushort, TimeStamp: ULONG, DosPath: UNICODE_STRING, }; pub const PPS_POST_PROCESS_INIT_ROUTINE = ?fn () callconv(.C) void; pub const FILE_BOTH_DIR_INFORMATION = extern struct { NextEntryOffset: ULONG, FileIndex: ULONG, CreationTime: LARGE_INTEGER, LastAccessTime: LARGE_INTEGER, LastWriteTime: LARGE_INTEGER, ChangeTime: LARGE_INTEGER, EndOfFile: LARGE_INTEGER, AllocationSize: LARGE_INTEGER, FileAttributes: ULONG, FileNameLength: ULONG, EaSize: ULONG, ShortNameLength: CHAR, ShortName: [12]WCHAR, FileName: [1]WCHAR, }; pub const FILE_BOTH_DIRECTORY_INFORMATION = FILE_BOTH_DIR_INFORMATION; pub const IO_APC_ROUTINE = fn (PVOID, *IO_STATUS_BLOCK, ULONG) callconv(.C) void; pub const CURDIR = extern struct { DosPath: UNICODE_STRING, Handle: HANDLE, }; pub const DUPLICATE_SAME_ACCESS = 2; pub const MODULEINFO = extern struct { lpBaseOfDll: LPVOID, SizeOfImage: DWORD, EntryPoint: LPVOID, }; pub const PSAPI_WS_WATCH_INFORMATION = extern struct { FaultingPc: LPVOID, FaultingVa: LPVOID, }; pub const PROCESS_MEMORY_COUNTERS = extern struct { cb: DWORD, PageFaultCount: DWORD, PeakWorkingSetSize: SIZE_T, WorkingSetSize: SIZE_T, QuotaPeakPagedPoolUsage: SIZE_T, QuotaPagedPoolUsage: SIZE_T, QuotaPeakNonPagedPoolUsage: SIZE_T, QuotaNonPagedPoolUsage: SIZE_T, PagefileUsage: SIZE_T, PeakPagefileUsage: SIZE_T, }; pub const PROCESS_MEMORY_COUNTERS_EX = extern struct { cb: DWORD, PageFaultCount: DWORD, PeakWorkingSetSize: SIZE_T, WorkingSetSize: SIZE_T, QuotaPeakPagedPoolUsage: SIZE_T, QuotaPagedPoolUsage: SIZE_T, QuotaPeakNonPagedPoolUsage: SIZE_T, QuotaNonPagedPoolUsage: SIZE_T, PagefileUsage: SIZE_T, PeakPagefileUsage: SIZE_T, PrivateUsage: SIZE_T, }; pub const PERFORMANCE_INFORMATION = extern struct { cb: DWORD, CommitTotal: SIZE_T, CommitLimit: SIZE_T, CommitPeak: SIZE_T, PhysicalTotal: SIZE_T, PhysicalAvailable: SIZE_T, SystemCache: SIZE_T, KernelTotal: SIZE_T, KernelPaged: SIZE_T, KernelNonpaged: SIZE_T, PageSize: SIZE_T, HandleCount: DWORD, ProcessCount: DWORD, ThreadCount: DWORD, }; pub const ENUM_PAGE_FILE_INFORMATION = extern struct { cb: DWORD, Reserved: DWORD, TotalSize: SIZE_T, TotalInUse: SIZE_T, PeakUsage: SIZE_T, }; pub const PENUM_PAGE_FILE_CALLBACKW = ?fn (?LPVOID, *ENUM_PAGE_FILE_INFORMATION, LPCWSTR) callconv(.C) BOOL; pub const PENUM_PAGE_FILE_CALLBACKA = ?fn (?LPVOID, *ENUM_PAGE_FILE_INFORMATION, LPCSTR) callconv(.C) BOOL; pub const PSAPI_WS_WATCH_INFORMATION_EX = extern struct { BasicInfo: PSAPI_WS_WATCH_INFORMATION, FaultingThreadId: ULONG_PTR, Flags: ULONG_PTR, }; pub const OSVERSIONINFOW = extern struct { dwOSVersionInfoSize: ULONG, dwMajorVersion: ULONG, dwMinorVersion: ULONG, dwBuildNumber: ULONG, dwPlatformId: ULONG, szCSDVersion: [128]WCHAR, }; pub const RTL_OSVERSIONINFOW = OSVERSIONINFOW; pub const REPARSE_DATA_BUFFER = extern struct { ReparseTag: ULONG, ReparseDataLength: USHORT, Reserved: USHORT, DataBuffer: [1]UCHAR, }; pub const SYMBOLIC_LINK_REPARSE_BUFFER = extern struct { SubstituteNameOffset: USHORT, SubstituteNameLength: USHORT, PrintNameOffset: USHORT, PrintNameLength: USHORT, Flags: ULONG, PathBuffer: [1]WCHAR, }; pub const MOUNT_POINT_REPARSE_BUFFER = extern struct { SubstituteNameOffset: USHORT, SubstituteNameLength: USHORT, PrintNameOffset: USHORT, PrintNameLength: USHORT, PathBuffer: [1]WCHAR, }; pub const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: ULONG = 16 * 1024; pub const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4; pub const FSCTL_GET_REPARSE_POINT: DWORD = 0x900a8; pub const IO_REPARSE_TAG_SYMLINK: ULONG = 0xa000000c; pub const IO_REPARSE_TAG_MOUNT_POINT: ULONG = 0xa0000003; pub const SYMLINK_FLAG_RELATIVE: ULONG = 0x1; pub const SYMBOLIC_LINK_FLAG_DIRECTORY: DWORD = 0x1; pub const SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: DWORD = 0x2; pub const MOUNTMGR_MOUNT_POINT = extern struct { SymbolicLinkNameOffset: ULONG, SymbolicLinkNameLength: USHORT, Reserved1: USHORT, UniqueIdOffset: ULONG, UniqueIdLength: USHORT, Reserved2: USHORT, DeviceNameOffset: ULONG, DeviceNameLength: USHORT, Reserved3: USHORT, }; pub const MOUNTMGR_MOUNT_POINTS = extern struct { Size: ULONG, NumberOfMountPoints: ULONG, MountPoints: [1]MOUNTMGR_MOUNT_POINT, }; pub const IOCTL_MOUNTMGR_QUERY_POINTS: ULONG = 0x6d0008; pub const OBJECT_INFORMATION_CLASS = enum(c_int) { ObjectBasicInformation = 0, ObjectNameInformation = 1, ObjectTypeInformation = 2, ObjectTypesInformation = 3, ObjectHandleFlagInformation = 4, ObjectSessionInformation = 5, MaxObjectInfoClass, }; pub const OBJECT_NAME_INFORMATION = extern struct { Name: UNICODE_STRING, }; pub const SRWLOCK = usize; pub const SRWLOCK_INIT: SRWLOCK = 0; pub const CONDITION_VARIABLE = usize; pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = 0; pub const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 0x1; pub const FILE_SKIP_SET_EVENT_ON_HANDLE = 0x2; pub const CTRL_C_EVENT: DWORD = 0; pub const CTRL_BREAK_EVENT: DWORD = 1; pub const CTRL_CLOSE_EVENT: DWORD = 2; pub const CTRL_LOGOFF_EVENT: DWORD = 5; pub const CTRL_SHUTDOWN_EVENT: DWORD = 6; pub const HANDLER_ROUTINE = fn (dwCtrlType: DWORD) callconv(.C) BOOL;
lib/std/os/windows.zig
usingnamespace std.os.linux; const std = @import("../../std.zig"); const errno = getErrno; const unexpectedErrno = std.os.unexpectedErrno; const expectEqual = std.testing.expectEqual; const expectError = std.testing.expectError; const expect = std.testing.expect; pub const btf = @import("bpf/btf.zig"); // instruction classes pub const LD = 0x00; pub const LDX = 0x01; pub const ST = 0x02; pub const STX = 0x03; pub const ALU = 0x04; pub const JMP = 0x05; pub const RET = 0x06; pub const MISC = 0x07; /// 32-bit pub const W = 0x00; /// 16-bit pub const H = 0x08; /// 8-bit pub const B = 0x10; /// 64-bit pub const DW = 0x18; pub const IMM = 0x00; pub const ABS = 0x20; pub const IND = 0x40; pub const MEM = 0x60; pub const LEN = 0x80; pub const MSH = 0xa0; // alu fields pub const ADD = 0x00; pub const SUB = 0x10; pub const MUL = 0x20; pub const DIV = 0x30; pub const OR = 0x40; pub const AND = 0x50; pub const LSH = 0x60; pub const RSH = 0x70; pub const NEG = 0x80; pub const MOD = 0x90; pub const XOR = 0xa0; // jmp fields pub const JA = 0x00; pub const JEQ = 0x10; pub const JGT = 0x20; pub const JGE = 0x30; pub const JSET = 0x40; //#define BPF_SRC(code) ((code) & 0x08) pub const K = 0x00; pub const X = 0x08; pub const MAXINSNS = 4096; // instruction classes /// jmp mode in word width pub const JMP32 = 0x06; /// alu mode in double word width pub const ALU64 = 0x07; // ld/ldx fields /// exclusive add pub const XADD = 0xc0; // alu/jmp fields /// mov reg to reg pub const MOV = 0xb0; /// sign extending arithmetic shift right */ pub const ARSH = 0xc0; // change endianness of a register /// flags for endianness conversion: pub const END = 0xd0; /// convert to little-endian */ pub const TO_LE = 0x00; /// convert to big-endian pub const TO_BE = 0x08; pub const FROM_LE = TO_LE; pub const FROM_BE = TO_BE; // jmp encodings /// jump != * pub const JNE = 0x50; /// LT is unsigned, '<' pub const JLT = 0xa0; /// LE is unsigned, '<=' * pub const JLE = 0xb0; /// SGT is signed '>', GT in x86 pub const JSGT = 0x60; /// SGE is signed '>=', GE in x86 pub const JSGE = 0x70; /// SLT is signed, '<' pub const JSLT = 0xc0; /// SLE is signed, '<=' pub const JSLE = 0xd0; /// function call pub const CALL = 0x80; /// function return pub const EXIT = 0x90; /// Flag for prog_attach command. If a sub-cgroup installs some bpf program, the /// program in this cgroup yields to sub-cgroup program. pub const F_ALLOW_OVERRIDE = 0x1; /// Flag for prog_attach command. If a sub-cgroup installs some bpf program, /// that cgroup program gets run in addition to the program in this cgroup. pub const F_ALLOW_MULTI = 0x2; /// Flag for prog_attach command. pub const F_REPLACE = 0x4; /// If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the verifier /// will perform strict alignment checking as if the kernel has been built with /// CONFIG_EFFICIENT_UNALIGNED_ACCESS not set, and NET_IP_ALIGN defined to 2. pub const F_STRICT_ALIGNMENT = 0x1; /// If BPF_F_ANY_ALIGNMENT is used in BPF_PROF_LOAD command, the verifier will /// allow any alignment whatsoever. On platforms with strict alignment /// requirements for loads ands stores (such as sparc and mips) the verifier /// validates that all loads and stores provably follow this requirement. This /// flag turns that checking and enforcement off. /// /// It is mostly used for testing when we want to validate the context and /// memory access aspects of the verifier, but because of an unaligned access /// the alignment check would trigger before the one we are interested in. pub const F_ANY_ALIGNMENT = 0x2; /// BPF_F_TEST_RND_HI32 is used in BPF_PROG_LOAD command for testing purpose. /// Verifier does sub-register def/use analysis and identifies instructions /// whose def only matters for low 32-bit, high 32-bit is never referenced later /// through implicit zero extension. Therefore verifier notifies JIT back-ends /// that it is safe to ignore clearing high 32-bit for these instructions. This /// saves some back-ends a lot of code-gen. However such optimization is not /// necessary on some arches, for example x86_64, arm64 etc, whose JIT back-ends /// hence hasn't used verifier's analysis result. But, we really want to have a /// way to be able to verify the correctness of the described optimization on /// x86_64 on which testsuites are frequently exercised. /// /// So, this flag is introduced. Once it is set, verifier will randomize high /// 32-bit for those instructions who has been identified as safe to ignore /// them. Then, if verifier is not doing correct analysis, such randomization /// will regress tests to expose bugs. pub const F_TEST_RND_HI32 = 0x4; /// When BPF ldimm64's insn[0].src_reg != 0 then this can have two extensions: /// insn[0].src_reg: BPF_PSEUDO_MAP_FD BPF_PSEUDO_MAP_VALUE /// insn[0].imm: map fd map fd /// insn[1].imm: 0 offset into value /// insn[0].off: 0 0 /// insn[1].off: 0 0 /// ldimm64 rewrite: address of map address of map[0]+offset /// verifier type: CONST_PTR_TO_MAP PTR_TO_MAP_VALUE pub const PSEUDO_MAP_FD = 1; pub const PSEUDO_MAP_VALUE = 2; /// when bpf_call->src_reg == BPF_PSEUDO_CALL, bpf_call->imm == pc-relative /// offset to another bpf function pub const PSEUDO_CALL = 1; /// flag for BPF_MAP_UPDATE_ELEM command. create new element or update existing pub const ANY = 0; /// flag for BPF_MAP_UPDATE_ELEM command. create new element if it didn't exist pub const NOEXIST = 1; /// flag for BPF_MAP_UPDATE_ELEM command. update existing element pub const EXIST = 2; /// flag for BPF_MAP_UPDATE_ELEM command. spin_lock-ed map_lookup/map_update pub const F_LOCK = 4; /// flag for BPF_MAP_CREATE command */ pub const BPF_F_NO_PREALLOC = 0x1; /// flag for BPF_MAP_CREATE command. Instead of having one common LRU list in /// the BPF_MAP_TYPE_LRU_[PERCPU_]HASH map, use a percpu LRU list which can /// scale and perform better. Note, the LRU nodes (including free nodes) cannot /// be moved across different LRU lists. pub const BPF_F_NO_COMMON_LRU = 0x2; /// flag for BPF_MAP_CREATE command. Specify numa node during map creation pub const BPF_F_NUMA_NODE = 0x4; /// flag for BPF_MAP_CREATE command. Flags for BPF object read access from /// syscall side pub const BPF_F_RDONLY = 0x8; /// flag for BPF_MAP_CREATE command. Flags for BPF object write access from /// syscall side pub const BPF_F_WRONLY = 0x10; /// flag for BPF_MAP_CREATE command. Flag for stack_map, store build_id+offset /// instead of pointer pub const BPF_F_STACK_BUILD_ID = 0x20; /// flag for BPF_MAP_CREATE command. Zero-initialize hash function seed. This /// should only be used for testing. pub const BPF_F_ZERO_SEED = 0x40; /// flag for BPF_MAP_CREATE command Flags for accessing BPF object from program /// side. pub const BPF_F_RDONLY_PROG = 0x80; /// flag for BPF_MAP_CREATE command. Flags for accessing BPF object from program /// side. pub const BPF_F_WRONLY_PROG = 0x100; /// flag for BPF_MAP_CREATE command. Clone map from listener for newly accepted /// socket pub const BPF_F_CLONE = 0x200; /// flag for BPF_MAP_CREATE command. Enable memory-mapping BPF map pub const BPF_F_MMAPABLE = 0x400; /// These values correspond to "syscalls" within the BPF program's environment, /// each one is documented in std.os.linux.BPF.kern pub const Helper = enum(i32) { unspec, map_lookup_elem, map_update_elem, map_delete_elem, probe_read, ktime_get_ns, trace_printk, get_prandom_u32, get_smp_processor_id, skb_store_bytes, l3_csum_replace, l4_csum_replace, tail_call, clone_redirect, get_current_pid_tgid, get_current_uid_gid, get_current_comm, get_cgroup_classid, skb_vlan_push, skb_vlan_pop, skb_get_tunnel_key, skb_set_tunnel_key, perf_event_read, redirect, get_route_realm, perf_event_output, skb_load_bytes, get_stackid, csum_diff, skb_get_tunnel_opt, skb_set_tunnel_opt, skb_change_proto, skb_change_type, skb_under_cgroup, get_hash_recalc, get_current_task, probe_write_user, current_task_under_cgroup, skb_change_tail, skb_pull_data, csum_update, set_hash_invalid, get_numa_node_id, skb_change_head, xdp_adjust_head, probe_read_str, get_socket_cookie, get_socket_uid, set_hash, setsockopt, skb_adjust_room, redirect_map, sk_redirect_map, sock_map_update, xdp_adjust_meta, perf_event_read_value, perf_prog_read_value, getsockopt, override_return, sock_ops_cb_flags_set, msg_redirect_map, msg_apply_bytes, msg_cork_bytes, msg_pull_data, bind, xdp_adjust_tail, skb_get_xfrm_state, get_stack, skb_load_bytes_relative, fib_lookup, sock_hash_update, msg_redirect_hash, sk_redirect_hash, lwt_push_encap, lwt_seg6_store_bytes, lwt_seg6_adjust_srh, lwt_seg6_action, rc_repeat, rc_keydown, skb_cgroup_id, get_current_cgroup_id, get_local_storage, sk_select_reuseport, skb_ancestor_cgroup_id, sk_lookup_tcp, sk_lookup_udp, sk_release, map_push_elem, map_pop_elem, map_peek_elem, msg_push_data, msg_pop_data, rc_pointer_rel, spin_lock, spin_unlock, sk_fullsock, tcp_sock, skb_ecn_set_ce, get_listener_sock, skc_lookup_tcp, tcp_check_syncookie, sysctl_get_name, sysctl_get_current_value, sysctl_get_new_value, sysctl_set_new_value, strtol, strtoul, sk_storage_get, sk_storage_delete, send_signal, tcp_gen_syncookie, skb_output, probe_read_user, probe_read_kernel, probe_read_user_str, probe_read_kernel_str, tcp_send_ack, send_signal_thread, jiffies64, read_branch_records, get_ns_current_pid_tgid, xdp_output, get_netns_cookie, get_current_ancestor_cgroup_id, sk_assign, ktime_get_boot_ns, seq_printf, seq_write, sk_cgroup_id, sk_ancestor_cgroup_id, ringbuf_output, ringbuf_reserve, ringbuf_submit, ringbuf_discard, ringbuf_query, csum_level, skc_to_tcp6_sock, skc_to_tcp_sock, skc_to_tcp_timewait_sock, skc_to_tcp_request_sock, skc_to_udp6_sock, get_task_stack, _, }; // TODO: determine that this is the expected bit layout for both little and big // endian systems /// a single BPF instruction pub const Insn = packed struct { code: u8, dst: u4, src: u4, off: i16, imm: i32, /// r0 - r9 are general purpose 64-bit registers, r10 points to the stack /// frame pub const Reg = packed enum(u4) { r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10 }; const Source = packed enum(u1) { reg, imm }; const Mode = packed enum(u8) { imm = IMM, abs = ABS, ind = IND, mem = MEM, len = LEN, msh = MSH, }; const AluOp = packed enum(u8) { add = ADD, sub = SUB, mul = MUL, div = DIV, alu_or = OR, alu_and = AND, lsh = LSH, rsh = RSH, neg = NEG, mod = MOD, xor = XOR, mov = MOV, arsh = ARSH, }; pub const Size = packed enum(u8) { byte = B, half_word = H, word = W, double_word = DW, }; const JmpOp = packed enum(u8) { ja = JA, jeq = JEQ, jgt = JGT, jge = JGE, jset = JSET, jlt = JLT, jle = JLE, jne = JNE, jsgt = JSGT, jsge = JSGE, jslt = JSLT, jsle = JSLE, }; const ImmOrReg = union(Source) { imm: i32, reg: Reg, }; fn imm_reg(code: u8, dst: Reg, src: anytype, off: i16) Insn { const imm_or_reg = if (@typeInfo(@TypeOf(src)) == .EnumLiteral) ImmOrReg{ .reg = @as(Reg, src) } else ImmOrReg{ .imm = src }; const src_type = switch (imm_or_reg) { .imm => K, .reg => X, }; return Insn{ .code = code | src_type, .dst = @enumToInt(dst), .src = switch (imm_or_reg) { .imm => 0, .reg => |r| @enumToInt(r), }, .off = off, .imm = switch (imm_or_reg) { .imm => |i| i, .reg => 0, }, }; } fn alu(comptime width: comptime_int, op: AluOp, dst: Reg, src: anytype) Insn { const width_bitfield = switch (width) { 32 => ALU, 64 => ALU64, else => @compileError("width must be 32 or 64"), }; return imm_reg(width_bitfield | @enumToInt(op), dst, src, 0); } pub fn mov(dst: Reg, src: anytype) Insn { return alu(64, .mov, dst, src); } pub fn add(dst: Reg, src: anytype) Insn { return alu(64, .add, dst, src); } pub fn sub(dst: Reg, src: anytype) Insn { return alu(64, .sub, dst, src); } pub fn mul(dst: Reg, src: anytype) Insn { return alu(64, .mul, dst, src); } pub fn div(dst: Reg, src: anytype) Insn { return alu(64, .div, dst, src); } pub fn alu_or(dst: Reg, src: anytype) Insn { return alu(64, .alu_or, dst, src); } pub fn alu_and(dst: Reg, src: anytype) Insn { return alu(64, .alu_and, dst, src); } pub fn lsh(dst: Reg, src: anytype) Insn { return alu(64, .lsh, dst, src); } pub fn rsh(dst: Reg, src: anytype) Insn { return alu(64, .rsh, dst, src); } pub fn neg(dst: Reg) Insn { return alu(64, .neg, dst, 0); } pub fn mod(dst: Reg, src: anytype) Insn { return alu(64, .mod, dst, src); } pub fn xor(dst: Reg, src: anytype) Insn { return alu(64, .xor, dst, src); } pub fn arsh(dst: Reg, src: anytype) Insn { return alu(64, .arsh, dst, src); } fn jmp(op: JmpOp, dst: Reg, src: anytype, off: i16) Insn { return imm_reg(JMP | @enumToInt(op), dst, src, off); } pub fn ja(off: i16) Insn { return jmp(.ja, .r0, 0, off); } pub fn jeq(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jeq, dst, src, off); } pub fn jgt(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jgt, dst, src, off); } pub fn jge(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jge, dst, src, off); } pub fn jlt(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jlt, dst, src, off); } pub fn jle(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jle, dst, src, off); } pub fn jset(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jset, dst, src, off); } pub fn jne(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jne, dst, src, off); } pub fn jsgt(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jsgt, dst, src, off); } pub fn jsge(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jsge, dst, src, off); } pub fn jslt(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jslt, dst, src, off); } pub fn jsle(dst: Reg, src: anytype, off: i16) Insn { return jmp(.jsle, dst, src, off); } pub fn xadd(dst: Reg, src: Reg) Insn { return Insn{ .code = STX | XADD | DW, .dst = @enumToInt(dst), .src = @enumToInt(src), .off = 0, .imm = 0, }; } fn ld(mode: Mode, size: Size, dst: Reg, src: Reg, imm: i32) Insn { return Insn{ .code = @enumToInt(mode) | @enumToInt(size) | LD, .dst = @enumToInt(dst), .src = @enumToInt(src), .off = 0, .imm = imm, }; } pub fn ld_abs(size: Size, dst: Reg, src: Reg, imm: i32) Insn { return ld(.abs, size, dst, src, imm); } pub fn ld_ind(size: Size, dst: Reg, src: Reg, imm: i32) Insn { return ld(.ind, size, dst, src, imm); } pub fn ldx(size: Size, dst: Reg, src: Reg, off: i16) Insn { return Insn{ .code = MEM | @enumToInt(size) | LDX, .dst = @enumToInt(dst), .src = @enumToInt(src), .off = off, .imm = 0, }; } fn ld_imm_impl1(dst: Reg, src: Reg, imm: u64) Insn { return Insn{ .code = LD | DW | IMM, .dst = @enumToInt(dst), .src = @enumToInt(src), .off = 0, .imm = @intCast(i32, @truncate(u32, imm)), }; } fn ld_imm_impl2(imm: u64) Insn { return Insn{ .code = 0, .dst = 0, .src = 0, .off = 0, .imm = @intCast(i32, @truncate(u32, imm >> 32)), }; } pub fn ld_dw1(dst: Reg, imm: u64) Insn { return ld_imm_impl1(dst, .r0, imm); } pub fn ld_dw2(imm: u64) Insn { return ld_imm_impl2(imm); } pub fn ld_map_fd1(dst: Reg, map_fd: fd_t) Insn { return ld_imm_impl1(dst, @intToEnum(Reg, PSEUDO_MAP_FD), @intCast(u64, map_fd)); } pub fn ld_map_fd2(map_fd: fd_t) Insn { return ld_imm_impl2(@intCast(u64, map_fd)); } pub fn st(comptime size: Size, dst: Reg, off: i16, imm: i32) Insn { if (size == .double_word) @compileError("TODO: need to determine how to correctly handle double words"); return Insn{ .code = MEM | @enumToInt(size) | ST, .dst = @enumToInt(dst), .src = 0, .off = off, .imm = imm, }; } pub fn stx(size: Size, dst: Reg, off: i16, src: Reg) Insn { return Insn{ .code = MEM | @enumToInt(size) | STX, .dst = @enumToInt(dst), .src = @enumToInt(src), .off = off, .imm = 0, }; } fn endian_swap(endian: std.builtin.Endian, comptime size: Size, dst: Reg) Insn { return Insn{ .code = switch (endian) { .Big => 0xdc, .Little => 0xd4, }, .dst = @enumToInt(dst), .src = 0, .off = 0, .imm = switch (size) { .byte => @compileError("can't swap a single byte"), .half_word => 16, .word => 32, .double_word => 64, }, }; } pub fn le(comptime size: Size, dst: Reg) Insn { return endian_swap(.Little, size, dst); } pub fn be(comptime size: Size, dst: Reg) Insn { return endian_swap(.Big, size, dst); } pub fn call(helper: Helper) Insn { return Insn{ .code = JMP | CALL, .dst = 0, .src = 0, .off = 0, .imm = @enumToInt(helper), }; } /// exit BPF program pub fn exit() Insn { return Insn{ .code = JMP | EXIT, .dst = 0, .src = 0, .off = 0, .imm = 0, }; } }; test "insn bitsize" { expectEqual(@bitSizeOf(Insn), 64); } fn expect_opcode(code: u8, insn: Insn) void { expectEqual(code, insn.code); } // The opcodes were grabbed from https://github.com/iovisor/bpf-docs/blob/master/eBPF.md test "opcodes" { // instructions that have a name that end with 1 or 2 are consecutive for // loading 64-bit immediates (imm is only 32 bits wide) // alu instructions expect_opcode(0x07, Insn.add(.r1, 0)); expect_opcode(0x0f, Insn.add(.r1, .r2)); expect_opcode(0x17, Insn.sub(.r1, 0)); expect_opcode(0x1f, Insn.sub(.r1, .r2)); expect_opcode(0x27, Insn.mul(.r1, 0)); expect_opcode(0x2f, Insn.mul(.r1, .r2)); expect_opcode(0x37, Insn.div(.r1, 0)); expect_opcode(0x3f, Insn.div(.r1, .r2)); expect_opcode(0x47, Insn.alu_or(.r1, 0)); expect_opcode(0x4f, Insn.alu_or(.r1, .r2)); expect_opcode(0x57, Insn.alu_and(.r1, 0)); expect_opcode(0x5f, Insn.alu_and(.r1, .r2)); expect_opcode(0x67, Insn.lsh(.r1, 0)); expect_opcode(0x6f, Insn.lsh(.r1, .r2)); expect_opcode(0x77, Insn.rsh(.r1, 0)); expect_opcode(0x7f, Insn.rsh(.r1, .r2)); expect_opcode(0x87, Insn.neg(.r1)); expect_opcode(0x97, Insn.mod(.r1, 0)); expect_opcode(0x9f, Insn.mod(.r1, .r2)); expect_opcode(0xa7, Insn.xor(.r1, 0)); expect_opcode(0xaf, Insn.xor(.r1, .r2)); expect_opcode(0xb7, Insn.mov(.r1, 0)); expect_opcode(0xbf, Insn.mov(.r1, .r2)); expect_opcode(0xc7, Insn.arsh(.r1, 0)); expect_opcode(0xcf, Insn.arsh(.r1, .r2)); // atomic instructions: might be more of these not documented in the wild expect_opcode(0xdb, Insn.xadd(.r1, .r2)); // TODO: byteswap instructions expect_opcode(0xd4, Insn.le(.half_word, .r1)); expectEqual(@intCast(i32, 16), Insn.le(.half_word, .r1).imm); expect_opcode(0xd4, Insn.le(.word, .r1)); expectEqual(@intCast(i32, 32), Insn.le(.word, .r1).imm); expect_opcode(0xd4, Insn.le(.double_word, .r1)); expectEqual(@intCast(i32, 64), Insn.le(.double_word, .r1).imm); expect_opcode(0xdc, Insn.be(.half_word, .r1)); expectEqual(@intCast(i32, 16), Insn.be(.half_word, .r1).imm); expect_opcode(0xdc, Insn.be(.word, .r1)); expectEqual(@intCast(i32, 32), Insn.be(.word, .r1).imm); expect_opcode(0xdc, Insn.be(.double_word, .r1)); expectEqual(@intCast(i32, 64), Insn.be(.double_word, .r1).imm); // memory instructions expect_opcode(0x18, Insn.ld_dw1(.r1, 0)); expect_opcode(0x00, Insn.ld_dw2(0)); // loading a map fd expect_opcode(0x18, Insn.ld_map_fd1(.r1, 0)); expectEqual(@intCast(u4, PSEUDO_MAP_FD), Insn.ld_map_fd1(.r1, 0).src); expect_opcode(0x00, Insn.ld_map_fd2(0)); expect_opcode(0x38, Insn.ld_abs(.double_word, .r1, .r2, 0)); expect_opcode(0x20, Insn.ld_abs(.word, .r1, .r2, 0)); expect_opcode(0x28, Insn.ld_abs(.half_word, .r1, .r2, 0)); expect_opcode(0x30, Insn.ld_abs(.byte, .r1, .r2, 0)); expect_opcode(0x58, Insn.ld_ind(.double_word, .r1, .r2, 0)); expect_opcode(0x40, Insn.ld_ind(.word, .r1, .r2, 0)); expect_opcode(0x48, Insn.ld_ind(.half_word, .r1, .r2, 0)); expect_opcode(0x50, Insn.ld_ind(.byte, .r1, .r2, 0)); expect_opcode(0x79, Insn.ldx(.double_word, .r1, .r2, 0)); expect_opcode(0x61, Insn.ldx(.word, .r1, .r2, 0)); expect_opcode(0x69, Insn.ldx(.half_word, .r1, .r2, 0)); expect_opcode(0x71, Insn.ldx(.byte, .r1, .r2, 0)); expect_opcode(0x62, Insn.st(.word, .r1, 0, 0)); expect_opcode(0x6a, Insn.st(.half_word, .r1, 0, 0)); expect_opcode(0x72, Insn.st(.byte, .r1, 0, 0)); expect_opcode(0x63, Insn.stx(.word, .r1, 0, .r2)); expect_opcode(0x6b, Insn.stx(.half_word, .r1, 0, .r2)); expect_opcode(0x73, Insn.stx(.byte, .r1, 0, .r2)); expect_opcode(0x7b, Insn.stx(.double_word, .r1, 0, .r2)); // branch instructions expect_opcode(0x05, Insn.ja(0)); expect_opcode(0x15, Insn.jeq(.r1, 0, 0)); expect_opcode(0x1d, Insn.jeq(.r1, .r2, 0)); expect_opcode(0x25, Insn.jgt(.r1, 0, 0)); expect_opcode(0x2d, Insn.jgt(.r1, .r2, 0)); expect_opcode(0x35, Insn.jge(.r1, 0, 0)); expect_opcode(0x3d, Insn.jge(.r1, .r2, 0)); expect_opcode(0xa5, Insn.jlt(.r1, 0, 0)); expect_opcode(0xad, Insn.jlt(.r1, .r2, 0)); expect_opcode(0xb5, Insn.jle(.r1, 0, 0)); expect_opcode(0xbd, Insn.jle(.r1, .r2, 0)); expect_opcode(0x45, Insn.jset(.r1, 0, 0)); expect_opcode(0x4d, Insn.jset(.r1, .r2, 0)); expect_opcode(0x55, Insn.jne(.r1, 0, 0)); expect_opcode(0x5d, Insn.jne(.r1, .r2, 0)); expect_opcode(0x65, Insn.jsgt(.r1, 0, 0)); expect_opcode(0x6d, Insn.jsgt(.r1, .r2, 0)); expect_opcode(0x75, Insn.jsge(.r1, 0, 0)); expect_opcode(0x7d, Insn.jsge(.r1, .r2, 0)); expect_opcode(0xc5, Insn.jslt(.r1, 0, 0)); expect_opcode(0xcd, Insn.jslt(.r1, .r2, 0)); expect_opcode(0xd5, Insn.jsle(.r1, 0, 0)); expect_opcode(0xdd, Insn.jsle(.r1, .r2, 0)); expect_opcode(0x85, Insn.call(.unspec)); expect_opcode(0x95, Insn.exit()); } pub const Cmd = extern enum(usize) { /// Create a map and return a file descriptor that refers to the map. The /// close-on-exec file descriptor flag is automatically enabled for the new /// file descriptor. /// /// uses MapCreateAttr map_create, /// Look up an element by key in a specified map and return its value. /// /// uses MapElemAttr map_lookup_elem, /// Create or update an element (key/value pair) in a specified map. /// /// uses MapElemAttr map_update_elem, /// Look up and delete an element by key in a specified map. /// /// uses MapElemAttr map_delete_elem, /// Look up an element by key in a specified map and return the key of the /// next element. map_get_next_key, /// Verify and load an eBPF program, returning a new file descriptor /// associated with the program. The close-on-exec file descriptor flag /// is automatically enabled for the new file descriptor. /// /// uses ProgLoadAttr prog_load, /// Pin a map or eBPF program to a path within the minimal BPF filesystem /// /// uses ObjAttr obj_pin, /// Get the file descriptor of a BPF object pinned to a certain path /// /// uses ObjAttr obj_get, /// uses ProgAttachAttr prog_attach, /// uses ProgAttachAttr prog_detach, /// uses TestRunAttr prog_test_run, /// uses GetIdAttr prog_get_next_id, /// uses GetIdAttr map_get_next_id, /// uses GetIdAttr prog_get_fd_by_id, /// uses GetIdAttr map_get_fd_by_id, /// uses InfoAttr obj_get_info_by_fd, /// uses QueryAttr prog_query, /// uses RawTracepointAttr raw_tracepoint_open, /// uses BtfLoadAttr btf_load, /// uses GetIdAttr btf_get_fd_by_id, /// uses TaskFdQueryAttr task_fd_query, /// uses MapElemAttr map_lookup_and_delete_elem, map_freeze, /// uses GetIdAttr btf_get_next_id, /// uses MapBatchAttr map_lookup_batch, /// uses MapBatchAttr map_lookup_and_delete_batch, /// uses MapBatchAttr map_update_batch, /// uses MapBatchAttr map_delete_batch, /// uses LinkCreateAttr link_create, /// uses LinkUpdateAttr link_update, /// uses GetIdAttr link_get_fd_by_id, /// uses GetIdAttr link_get_next_id, /// uses EnableStatsAttr enable_stats, /// uses IterCreateAttr iter_create, link_detach, _, }; pub const MapType = extern enum(u32) { unspec, hash, array, prog_array, perf_event_array, percpu_hash, percpu_array, stack_trace, cgroup_array, lru_hash, lru_percpu_hash, lpm_trie, array_of_maps, hash_of_maps, devmap, sockmap, cpumap, xskmap, sockhash, cgroup_storage, reuseport_sockarray, percpu_cgroup_storage, queue, stack, sk_storage, devmap_hash, struct_ops, /// An ordered and shared CPU version of perf_event_array. They have /// similar semantics: /// - variable length records /// - no blocking: when full, reservation fails /// - memory mappable for ease and speed /// - epoll notifications for new data, but can busy poll /// /// Ringbufs give BPF programs two sets of APIs: /// - ringbuf_output() allows copy data from one place to a ring /// buffer, similar to bpf_perf_event_output() /// - ringbuf_reserve()/ringbuf_commit()/ringbuf_discard() split the /// process into two steps. First a fixed amount of space is reserved, /// if that is successful then the program gets a pointer to a chunk of /// memory and can be submitted with commit() or discarded with /// discard() /// /// ringbuf_output() will incurr an extra memory copy, but allows to submit /// records of the length that's not known beforehand, and is an easy /// replacement for perf_event_outptu(). /// /// ringbuf_reserve() avoids the extra memory copy but requires a known size /// of memory beforehand. /// /// ringbuf_query() allows to query properties of the map, 4 are currently /// supported: /// - BPF_RB_AVAIL_DATA: amount of unconsumed data in ringbuf /// - BPF_RB_RING_SIZE: returns size of ringbuf /// - BPF_RB_CONS_POS/BPF_RB_PROD_POS returns current logical position /// of consumer and producer respectively /// /// key size: 0 /// value size: 0 /// max entries: size of ringbuf, must be power of 2 ringbuf, _, }; pub const ProgType = extern enum(u32) { unspec, /// context type: __sk_buff socket_filter, /// context type: bpf_user_pt_regs_t kprobe, /// context type: __sk_buff sched_cls, /// context type: __sk_buff sched_act, /// context type: u64 tracepoint, /// context type: xdp_md xdp, /// context type: bpf_perf_event_data perf_event, /// context type: __sk_buff cgroup_skb, /// context type: bpf_sock cgroup_sock, /// context type: __sk_buff lwt_in, /// context type: __sk_buff lwt_out, /// context type: __sk_buff lwt_xmit, /// context type: bpf_sock_ops sock_ops, /// context type: __sk_buff sk_skb, /// context type: bpf_cgroup_dev_ctx cgroup_device, /// context type: sk_msg_md sk_msg, /// context type: bpf_raw_tracepoint_args raw_tracepoint, /// context type: bpf_sock_addr cgroup_sock_addr, /// context type: __sk_buff lwt_seg6local, /// context type: u32 lirc_mode2, /// context type: sk_reuseport_md sk_reuseport, /// context type: __sk_buff flow_dissector, /// context type: bpf_sysctl cgroup_sysctl, /// context type: bpf_raw_tracepoint_args raw_tracepoint_writable, /// context type: bpf_sockopt cgroup_sockopt, /// context type: void * tracing, /// context type: void * struct_ops, /// context type: void * ext, /// context type: void * lsm, /// context type: bpf_sk_lookup sk_lookup, _, }; pub const AttachType = extern enum(u32) { cgroup_inet_ingress, cgroup_inet_egress, cgroup_inet_sock_create, cgroup_sock_ops, sk_skb_stream_parser, sk_skb_stream_verdict, cgroup_device, sk_msg_verdict, cgroup_inet4_bind, cgroup_inet6_bind, cgroup_inet4_connect, cgroup_inet6_connect, cgroup_inet4_post_bind, cgroup_inet6_post_bind, cgroup_udp4_sendmsg, cgroup_udp6_sendmsg, lirc_mode2, flow_dissector, cgroup_sysctl, cgroup_udp4_recvmsg, cgroup_udp6_recvmsg, cgroup_getsockopt, cgroup_setsockopt, trace_raw_tp, trace_fentry, trace_fexit, modify_return, lsm_mac, trace_iter, cgroup_inet4_getpeername, cgroup_inet6_getpeername, cgroup_inet4_getsockname, cgroup_inet6_getsockname, xdp_devmap, cgroup_inet_sock_release, xdp_cpumap, sk_lookup, xdp, _, }; const obj_name_len = 16; /// struct used by Cmd.map_create command pub const MapCreateAttr = extern struct { /// one of MapType map_type: u32, /// size of key in bytes key_size: u32, /// size of value in bytes value_size: u32, /// max number of entries in a map max_entries: u32, /// .map_create related flags map_flags: u32, /// fd pointing to the inner map inner_map_fd: fd_t, /// numa node (effective only if MapCreateFlags.numa_node is set) numa_node: u32, map_name: [obj_name_len]u8, /// ifindex of netdev to create on map_ifindex: u32, /// fd pointing to a BTF type data btf_fd: fd_t, /// BTF type_id of the key btf_key_type_id: u32, /// BTF type_id of the value bpf_value_type_id: u32, /// BTF type_id of a kernel struct stored as the map value btf_vmlinux_value_type_id: u32, }; /// struct used by Cmd.map_*_elem commands pub const MapElemAttr = extern struct { map_fd: fd_t, key: u64, result: extern union { value: u64, next_key: u64, }, flags: u64, }; /// struct used by Cmd.map_*_batch commands pub const MapBatchAttr = extern struct { /// start batch, NULL to start from beginning in_batch: u64, /// output: next start batch out_batch: u64, keys: u64, values: u64, /// input/output: /// input: # of key/value elements /// output: # of filled elements count: u32, map_fd: fd_t, elem_flags: u64, flags: u64, }; /// struct used by Cmd.prog_load command pub const ProgLoadAttr = extern struct { /// one of ProgType prog_type: u32, insn_cnt: u32, insns: u64, license: u64, /// verbosity level of verifier log_level: u32, /// size of user buffer log_size: u32, /// user supplied buffer log_buf: u64, /// not used kern_version: u32, prog_flags: u32, prog_name: [obj_name_len]u8, /// ifindex of netdev to prep for. prog_ifindex: u32, /// For some prog types expected attach type must be known at load time to /// verify attach type specific parts of prog (context accesses, allowed /// helpers, etc). expected_attach_type: u32, /// fd pointing to BTF type data prog_btf_fd: fd_t, /// userspace bpf_func_info size func_info_rec_size: u32, func_info: u64, /// number of bpf_func_info records func_info_cnt: u32, /// userspace bpf_line_info size line_info_rec_size: u32, line_info: u64, /// number of bpf_line_info records line_info_cnt: u32, /// in-kernel BTF type id to attach to attact_btf_id: u32, /// 0 to attach to vmlinux attach_prog_id: u32, }; /// struct used by Cmd.obj_* commands pub const ObjAttr = extern struct { pathname: u64, bpf_fd: fd_t, file_flags: u32, }; /// struct used by Cmd.prog_attach/detach commands pub const ProgAttachAttr = extern struct { /// container object to attach to target_fd: fd_t, /// eBPF program to attach attach_bpf_fd: fd_t, attach_type: u32, attach_flags: u32, // TODO: BPF_F_REPLACE flags /// previously attached eBPF program to replace if .replace is used replace_bpf_fd: fd_t, }; /// struct used by Cmd.prog_test_run command pub const TestRunAttr = extern struct { prog_fd: fd_t, retval: u32, /// input: len of data_in data_size_in: u32, /// input/output: len of data_out. returns ENOSPC if data_out is too small. data_size_out: u32, data_in: u64, data_out: u64, repeat: u32, duration: u32, /// input: len of ctx_in ctx_size_in: u32, /// input/output: len of ctx_out. returns ENOSPC if ctx_out is too small. ctx_size_out: u32, ctx_in: u64, ctx_out: u64, }; /// struct used by Cmd.*_get_*_id commands pub const GetIdAttr = extern struct { id: extern union { start_id: u32, prog_id: u32, map_id: u32, btf_id: u32, link_id: u32, }, next_id: u32, open_flags: u32, }; /// struct used by Cmd.obj_get_info_by_fd command pub const InfoAttr = extern struct { bpf_fd: fd_t, info_len: u32, info: u64, }; /// struct used by Cmd.prog_query command pub const QueryAttr = extern struct { /// container object to query target_fd: fd_t, attach_type: u32, query_flags: u32, attach_flags: u32, prog_ids: u64, prog_cnt: u32, }; /// struct used by Cmd.raw_tracepoint_open command pub const RawTracepointAttr = extern struct { name: u64, prog_fd: fd_t, }; /// struct used by Cmd.btf_load command pub const BtfLoadAttr = extern struct { btf: u64, btf_log_buf: u64, btf_size: u32, btf_log_size: u32, btf_log_level: u32, }; /// struct used by Cmd.task_fd_query pub const TaskFdQueryAttr = extern struct { /// input: pid pid: pid_t, /// input: fd fd: fd_t, /// input: flags flags: u32, /// input/output: buf len buf_len: u32, /// input/output: /// tp_name for tracepoint /// symbol for kprobe /// filename for uprobe buf: u64, /// output: prod_id prog_id: u32, /// output: BPF_FD_TYPE fd_type: u32, /// output: probe_offset probe_offset: u64, /// output: probe_addr probe_addr: u64, }; /// struct used by Cmd.link_create command pub const LinkCreateAttr = extern struct { /// eBPF program to attach prog_fd: fd_t, /// object to attach to target_fd: fd_t, attach_type: u32, /// extra flags flags: u32, }; /// struct used by Cmd.link_update command pub const LinkUpdateAttr = extern struct { link_fd: fd_t, /// new program to update link with new_prog_fd: fd_t, /// extra flags flags: u32, /// expected link's program fd, it is specified only if BPF_F_REPLACE is /// set in flags old_prog_fd: fd_t, }; /// struct used by Cmd.enable_stats command pub const EnableStatsAttr = extern struct { type: u32, }; /// struct used by Cmd.iter_create command pub const IterCreateAttr = extern struct { link_fd: fd_t, flags: u32, }; /// Mega struct that is passed to the bpf() syscall pub const Attr = extern union { map_create: MapCreateAttr, map_elem: MapElemAttr, map_batch: MapBatchAttr, prog_load: ProgLoadAttr, obj: ObjAttr, prog_attach: ProgAttachAttr, test_run: TestRunAttr, get_id: GetIdAttr, info: InfoAttr, query: QueryAttr, raw_tracepoint: RawTracepointAttr, btf_load: BtfLoadAttr, task_fd_query: TaskFdQueryAttr, link_create: LinkCreateAttr, link_update: LinkUpdateAttr, enable_stats: EnableStatsAttr, iter_create: IterCreateAttr, }; pub const Log = struct { level: u32, buf: []u8, }; pub fn map_create(map_type: MapType, key_size: u32, value_size: u32, max_entries: u32) !fd_t { var attr = Attr{ .map_create = std.mem.zeroes(MapCreateAttr), }; attr.map_create.map_type = @enumToInt(map_type); attr.map_create.key_size = key_size; attr.map_create.value_size = value_size; attr.map_create.max_entries = max_entries; const rc = bpf(.map_create, &attr, @sizeOf(MapCreateAttr)); return switch (errno(rc)) { 0 => @intCast(fd_t, rc), EINVAL => error.MapTypeOrAttrInvalid, ENOMEM => error.SystemResources, EPERM => error.AccessDenied, else => |err| unexpectedErrno(rc), }; } test "map_create" { const map = try map_create(.hash, 4, 4, 32); defer std.os.close(map); } pub fn map_lookup_elem(fd: fd_t, key: []const u8, value: []u8) !void { var attr = Attr{ .map_elem = std.mem.zeroes(MapElemAttr), }; attr.map_elem.map_fd = fd; attr.map_elem.key = @ptrToInt(key.ptr); attr.map_elem.result.value = @ptrToInt(value.ptr); const rc = bpf(.map_lookup_elem, &attr, @sizeOf(MapElemAttr)); switch (errno(rc)) { 0 => return, EBADF => return error.BadFd, EFAULT => unreachable, EINVAL => return error.FieldInAttrNeedsZeroing, ENOENT => return error.NotFound, EPERM => return error.AccessDenied, else => |err| return unexpectedErrno(rc), } } pub fn map_update_elem(fd: fd_t, key: []const u8, value: []const u8, flags: u64) !void { var attr = Attr{ .map_elem = std.mem.zeroes(MapElemAttr), }; attr.map_elem.map_fd = fd; attr.map_elem.key = @ptrToInt(key.ptr); attr.map_elem.result = .{ .value = @ptrToInt(value.ptr) }; attr.map_elem.flags = flags; const rc = bpf(.map_update_elem, &attr, @sizeOf(MapElemAttr)); switch (errno(rc)) { 0 => return, E2BIG => return error.ReachedMaxEntries, EBADF => return error.BadFd, EFAULT => unreachable, EINVAL => return error.FieldInAttrNeedsZeroing, ENOMEM => return error.SystemResources, EPERM => return error.AccessDenied, else => |err| return unexpectedErrno(err), } } pub fn map_delete_elem(fd: fd_t, key: []const u8) !void { var attr = Attr{ .map_elem = std.mem.zeroes(MapElemAttr), }; attr.map_elem.map_fd = fd; attr.map_elem.key = @ptrToInt(key.ptr); const rc = bpf(.map_delete_elem, &attr, @sizeOf(MapElemAttr)); switch (errno(rc)) { 0 => return, EBADF => return error.BadFd, EFAULT => unreachable, EINVAL => return error.FieldInAttrNeedsZeroing, ENOENT => return error.NotFound, EPERM => return error.AccessDenied, else => |err| return unexpectedErrno(err), } } test "map lookup, update, and delete" { const key_size = 4; const value_size = 4; const map = try map_create(.hash, key_size, value_size, 1); defer std.os.close(map); const key = std.mem.zeroes([key_size]u8); var value = std.mem.zeroes([value_size]u8); // fails looking up value that doesn't exist expectError(error.NotFound, map_lookup_elem(map, &key, &value)); // succeed at updating and looking up element try map_update_elem(map, &key, &value, 0); try map_lookup_elem(map, &key, &value); // fails inserting more than max entries const second_key = [key_size]u8{ 0, 0, 0, 1 }; expectError(error.ReachedMaxEntries, map_update_elem(map, &second_key, &value, 0)); // succeed at deleting an existing elem try map_delete_elem(map, &key); expectError(error.NotFound, map_lookup_elem(map, &key, &value)); // fail at deleting a non-existing elem expectError(error.NotFound, map_delete_elem(map, &key)); } pub fn prog_load( prog_type: ProgType, insns: []const Insn, log: ?*Log, license: []const u8, kern_version: u32, ) !fd_t { var attr = Attr{ .prog_load = std.mem.zeroes(ProgLoadAttr), }; attr.prog_load.prog_type = @enumToInt(prog_type); attr.prog_load.insns = @ptrToInt(insns.ptr); attr.prog_load.insn_cnt = @intCast(u32, insns.len); attr.prog_load.license = @ptrToInt(license.ptr); attr.prog_load.kern_version = kern_version; if (log) |l| { attr.prog_load.log_buf = @ptrToInt(l.buf.ptr); attr.prog_load.log_size = @intCast(u32, l.buf.len); attr.prog_load.log_level = l.level; } const rc = bpf(.prog_load, &attr, @sizeOf(ProgLoadAttr)); return switch (errno(rc)) { 0 => @intCast(fd_t, rc), EACCES => error.UnsafeProgram, EFAULT => unreachable, EINVAL => error.InvalidProgram, EPERM => error.AccessDenied, else => |err| unexpectedErrno(err), }; } test "prog_load" { // this should fail because it does not set r0 before exiting const bad_prog = [_]Insn{ Insn.exit(), }; const good_prog = [_]Insn{ Insn.mov(.r0, 0), Insn.exit(), }; const prog = try prog_load(.socket_filter, &good_prog, null, "MIT", 0); defer std.os.close(prog); expectError(error.UnsafeProgram, prog_load(.socket_filter, &bad_prog, null, "MIT", 0)); }
lib/std/os/linux/bpf.zig
const std = @import("std"); const c = @cImport({ @cInclude("time.h"); @cInclude("sys/select.h"); @cInclude("poll.h"); }); pub var memory = [_]u16{0} ** 65536; pub var reg = [_]u16{0} ** @enumToInt(Registers.COUNT); pub const Registers = enum(u16) { R0, R1, R2, R3, R4, R5, R6, R7, PC, // program counter COND, COUNT, pub fn val(self: Registers) u16 { return @enumToInt(self); } }; pub const ConditionFlags = enum(u16) { POS = 1 << 0, ZRO = 1 << 1, NEG = 1 << 2, pub fn val(self: ConditionFlags) u16 { return @enumToInt(self); } }; const MemoryMappedRegisters = enum(u16) { KBSR = 0xFE00, KBDR = 0xFE02, pub fn val(self: MemoryMappedRegisters) u16 { return @enumToInt(self); } }; pub fn clearMemory() void { // Reset registers var i: usize = 0; while (i < reg.len) { reg[i] = 0; i += 1; } // Clear RAM i = 0; while (i < memory.len) { memory[i] = 0; i += 1; } } test "clearMemory" { reg[0] = 10; const expected_empty = [_]u16{0} ** reg.len; const expected_with_change = [_]u16{10, 0, 0}; try std.testing.expectEqualSlices(u16, expected_with_change[0..], reg[0..3]); clearMemory(); try std.testing.expectEqualSlices(u16, expected_empty[0..], reg[0..]); } fn checkKeyboard() bool { var readfds: c.fd_set = undefined; // Looks like Zig's c-translate can't convert these macros? // c.FD_ZERO(&readfds); // c.FD_SET(std.os.linux.STDIN_FILENO, &readfds); var timeout: c.timeval = undefined; timeout.tv_sec = 0; timeout.tv_usec = 0; return c.select(1, &readfds, 0, 0, &timeout) != 0; } fn checkKeyboardPoll() bool { var fds: c.pollfd = c.pollfd { .fd = std.os.linux.STDIN_FILENO, .events = 0, .revents = 0, }; return c.poll(&fds, 1, -1) != 0; } pub fn read(addr: u16) u16 { if (addr == MemoryMappedRegisters.KBSR.val()) { if (checkKeyboardPoll()) { memory[MemoryMappedRegisters.KBSR.val()] = 1 << 15; memory[MemoryMappedRegisters.KBDR.val()] = @as(u16, std.io.getStdIn().reader().readByte() catch unreachable); } else { memory[MemoryMappedRegisters.KBSR.val()] = 0; } } return memory[addr]; } pub fn write(addr: u16, val: u16) void { memory[addr] = val; }
src/mem.zig
const c = @import("c.zig"); const std = @import("std"); const panic = std.debug.panic; const trait = std.meta.trait; //TODO Replace with pipeline state object pub fn init3dRendering() void { c.glEnable(c.GL_DEPTH_TEST); c.glDepthMask(c.GL_TRUE); c.glDepthFunc(c.GL_LESS); c.glFrontFace(c.GL_CCW); c.glEnable(c.GL_CULL_FACE); c.glCullFace(c.GL_BACK); c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0); } pub fn clearFramebuffer() void { //Need to enable depth test to clear depth buffer c.glEnable(c.GL_DEPTH_TEST); c.glDepthMask(c.GL_TRUE); c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT); } pub fn setViewport(size: [2]i32) void { c.glViewport(0, 0, @intCast(c.GLsizei, size[0]), @intCast(c.GLsizei, size[1])); } pub const Mesh = struct { const Self = @This(); vao: c.GLuint, vertex_buffer: c.GLuint, index_buffer: c.GLuint, index_count: c.GLint, index_type: c.GLenum, fn isVertexTypeValid(comptime VertexType: type) void { if(!comptime trait.hasFn("genVao")(VertexType)) { @compileError("VertexType doesn't have genVao Function"); } } fn getIndexType(comptime IndexType: type) c.GLenum { var index_type: c.GLenum = undefined; if(comptime IndexType == u8) { return c.GL_UNSIGNED_BYTE; } else if(comptime IndexType == u16) { return c.GL_UNSIGNED_SHORT; } else if(comptime IndexType == u32) { return c.GL_UNSIGNED_INT; } else { @compileError("IndexType must be u8, u16, or u32"); } } pub fn init(comptime VertexType: type, comptime IndexType: type, vertices: []const VertexType, indices: []const IndexType) Self { //Validate Types comptime isVertexTypeValid(VertexType); const index_type: c.GLenum = comptime getIndexType(IndexType); var vao: c.GLuint = undefined; c.glGenVertexArrays(1, &vao); c.glBindVertexArray(vao); var buffers: [2]c.GLuint = undefined; c.glGenBuffers(buffers.len, &buffers); c.glBindBuffer(c.GL_ARRAY_BUFFER, buffers[0]); c.glBufferData(c.GL_ARRAY_BUFFER, @intCast(c_longlong, @sizeOf(VertexType) * vertices.len), vertices.ptr, c.GL_STATIC_DRAW); VertexType.genVao(); c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, buffers[1]); c.glBufferData(c.GL_ELEMENT_ARRAY_BUFFER, @intCast(c_longlong, @sizeOf(u32) * indices.len), indices.ptr, c.GL_STATIC_DRAW); c.glBindVertexArray(0); c.glBindBuffer(c.GL_ARRAY_BUFFER,0); c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, 0); return Self { .vao = vao, .vertex_buffer = buffers[0], .index_buffer = buffers[1], .index_count = @intCast(c.GLint, indices.len), .index_type = index_type, }; } pub fn deinit(self: *const Self) void { c.glDeleteVertexArrays(1, &self.vao); c.glDeleteBuffers(1, &self.vertex_buffer); c.glDeleteBuffers(1, &self.index_buffer); } pub fn draw(self: *const Self) void { //Setup c.glBindVertexArray(self.vao); c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, self.index_buffer); //Draw c.glDrawElements(c.GL_TRIANGLES, self.index_count, self.index_type, null); //Cleanup c.glBindVertexArray(0); c.glBindBuffer(c.GL_ARRAY_BUFFER,0); c.glBindBuffer(c.GL_ELEMENT_ARRAY_BUFFER, 0); } }; pub const Shader = struct { const Self = @This(); shader_program: c.GLuint, pub fn init(vertex_shader: []const u8, fragment_shader: []const u8) Self { const stdout = std.io.getStdOut().writer(); var program = c.glCreateProgram(); var vertex_module = Self.init_shader_module(vertex_shader, c.GL_VERTEX_SHADER); c.glAttachShader(program, vertex_module); var fragment_module = Self.init_shader_module(fragment_shader, c.GL_FRAGMENT_SHADER); c.glAttachShader(program, fragment_module); c.glLinkProgram(program); var program_info_size: c.GLint = undefined; c.glGetProgramiv(program, c.GL_INFO_LOG_LENGTH, &program_info_size); if (program_info_size > 0) { var program_info_string = [_]u8{0} ** 512; c.glGetProgramInfoLog(program, @intCast(c.GLsizei, program_info_string.len ), null, &program_info_string); stdout.print("Shader Error: {s}!\n", .{program_info_string}) catch {}; } c.glDeleteShader(vertex_module); c.glDeleteShader(fragment_module); return Self { .shader_program = program, }; } pub fn deinit(self: *Self) void { c.glDeleteProgram(self.shader_program); } fn init_shader_module(shader_code: []const u8, stage: c.GLuint) c.GLuint { var shader = c.glCreateShader(stage); c.glShaderSource(shader, 1, &shader_code.ptr, &@intCast(c.GLint, shader_code.len)); c.glCompileShader(shader); return shader; } }; pub const Texture = struct { const Self = @This(); handle: c.GLuint, //TODO format + sampling pub fn init(size: [2]u32, data: []const u8) Self { var texture: c.GLuint = undefined; c.glGenTextures(1, &texture); c.glBindTexture(c.GL_TEXTURE_2D, texture); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_WRAP_S, c.GL_REPEAT); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_WRAP_T, c.GL_REPEAT); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MIN_FILTER, c.GL_NEAREST); c.glTexParameteri(c.GL_TEXTURE_2D, c.GL_TEXTURE_MAG_FILTER, c.GL_NEAREST); c.glTexImage2D(c.GL_TEXTURE_2D, 0, c.GL_RGBA, @intCast(c.GLsizei, size[0]), @intCast(c.GLsizei, size[1]), 0, c.GL_RGBA, c.GL_UNSIGNED_BYTE, data.ptr); return Self{ .handle = texture, }; } pub fn deinit(self: *Self) void { c.glDeleteTextures(1, &self.handle); } pub fn bind(self: *Self, index: u32) void { c.glActiveTexture(c.GL_TEXTURE0 + index); c.glBindTexture(c.GL_TEXTURE_2D, self.handle); } };
src/opengl_renderer.zig
/// The function fiatSecp256k1AddcarryxU32 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^32 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] fn fiatSecp256k1AddcarryxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u64 = ((@intCast(u64, arg1) + @intCast(u64, arg2)) + @intCast(u64, arg3)); const x2: u32 = @intCast(u32, (x1 & @intCast(u64, 0xffffffff))); const x3: u1 = @intCast(u1, (x1 >> 32)); out1.* = x2; out2.* = x3; } /// The function fiatSecp256k1SubborrowxU32 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^32 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] fn fiatSecp256k1SubborrowxU32(out1: *u32, out2: *u1, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: i64 = ((@intCast(i64, arg2) - @intCast(i64, arg1)) - @intCast(i64, arg3)); const x2: i1 = @intCast(i1, (x1 >> 32)); const x3: u32 = @intCast(u32, (x1 & @intCast(i64, 0xffffffff))); out1.* = x3; out2.* = @intCast(u1, (@intCast(i2, 0x0) - @intCast(i2, x2))); } /// The function fiatSecp256k1MulxU32 is a multiplication, returning the full double-width result. /// Postconditions: /// out1 = (arg1 * arg2) mod 2^32 /// out2 = ⌊arg1 * arg2 / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffff] /// arg2: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0xffffffff] fn fiatSecp256k1MulxU32(out1: *u32, out2: *u32, arg1: u32, arg2: u32) callconv(.Inline) void { const x1: u64 = (@intCast(u64, arg1) * @intCast(u64, arg2)); const x2: u32 = @intCast(u32, (x1 & @intCast(u64, 0xffffffff))); const x3: u32 = @intCast(u32, (x1 >> 32)); out1.* = x2; out2.* = x3; } /// The function fiatSecp256k1CmovznzU32 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] fn fiatSecp256k1CmovznzU32(out1: *u32, arg1: u1, arg2: u32, arg3: u32) callconv(.Inline) void { const x1: u1 = (~(~arg1)); const x2: u32 = @intCast(u32, (@intCast(i64, @intCast(i1, (@intCast(i2, 0x0) - @intCast(i2, x1)))) & @intCast(i64, 0xffffffff))); const x3: u32 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function fiatSecp256k1Mul multiplies two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Mul(out1: *[8]u32, arg1: [8]u32, arg2: [8]u32) void { const x1: u32 = (arg1[1]); const x2: u32 = (arg1[2]); const x3: u32 = (arg1[3]); const x4: u32 = (arg1[4]); const x5: u32 = (arg1[5]); const x6: u32 = (arg1[6]); const x7: u32 = (arg1[7]); const x8: u32 = (arg1[0]); var x9: u32 = undefined; var x10: u32 = undefined; fiatSecp256k1MulxU32(&x9, &x10, x8, (arg2[7])); var x11: u32 = undefined; var x12: u32 = undefined; fiatSecp256k1MulxU32(&x11, &x12, x8, (arg2[6])); var x13: u32 = undefined; var x14: u32 = undefined; fiatSecp256k1MulxU32(&x13, &x14, x8, (arg2[5])); var x15: u32 = undefined; var x16: u32 = undefined; fiatSecp256k1MulxU32(&x15, &x16, x8, (arg2[4])); var x17: u32 = undefined; var x18: u32 = undefined; fiatSecp256k1MulxU32(&x17, &x18, x8, (arg2[3])); var x19: u32 = undefined; var x20: u32 = undefined; fiatSecp256k1MulxU32(&x19, &x20, x8, (arg2[2])); var x21: u32 = undefined; var x22: u32 = undefined; fiatSecp256k1MulxU32(&x21, &x22, x8, (arg2[1])); var x23: u32 = undefined; var x24: u32 = undefined; fiatSecp256k1MulxU32(&x23, &x24, x8, (arg2[0])); var x25: u32 = undefined; var x26: u1 = undefined; fiatSecp256k1AddcarryxU32(&x25, &x26, 0x0, x24, x21); var x27: u32 = undefined; var x28: u1 = undefined; fiatSecp256k1AddcarryxU32(&x27, &x28, x26, x22, x19); var x29: u32 = undefined; var x30: u1 = undefined; fiatSecp256k1AddcarryxU32(&x29, &x30, x28, x20, x17); var x31: u32 = undefined; var x32: u1 = undefined; fiatSecp256k1AddcarryxU32(&x31, &x32, x30, x18, x15); var x33: u32 = undefined; var x34: u1 = undefined; fiatSecp256k1AddcarryxU32(&x33, &x34, x32, x16, x13); var x35: u32 = undefined; var x36: u1 = undefined; fiatSecp256k1AddcarryxU32(&x35, &x36, x34, x14, x11); var x37: u32 = undefined; var x38: u1 = undefined; fiatSecp256k1AddcarryxU32(&x37, &x38, x36, x12, x9); const x39: u32 = (@intCast(u32, x38) + x10); var x40: u32 = undefined; var x41: u32 = undefined; fiatSecp256k1MulxU32(&x40, &x41, x23, 0xd2253531); var x42: u32 = undefined; var x43: u32 = undefined; fiatSecp256k1MulxU32(&x42, &x43, x40, 0xffffffff); var x44: u32 = undefined; var x45: u32 = undefined; fiatSecp256k1MulxU32(&x44, &x45, x40, 0xffffffff); var x46: u32 = undefined; var x47: u32 = undefined; fiatSecp256k1MulxU32(&x46, &x47, x40, 0xffffffff); var x48: u32 = undefined; var x49: u32 = undefined; fiatSecp256k1MulxU32(&x48, &x49, x40, 0xffffffff); var x50: u32 = undefined; var x51: u32 = undefined; fiatSecp256k1MulxU32(&x50, &x51, x40, 0xffffffff); var x52: u32 = undefined; var x53: u32 = undefined; fiatSecp256k1MulxU32(&x52, &x53, x40, 0xffffffff); var x54: u32 = undefined; var x55: u32 = undefined; fiatSecp256k1MulxU32(&x54, &x55, x40, 0xfffffffe); var x56: u32 = undefined; var x57: u32 = undefined; fiatSecp256k1MulxU32(&x56, &x57, x40, 0xfffffc2f); var x58: u32 = undefined; var x59: u1 = undefined; fiatSecp256k1AddcarryxU32(&x58, &x59, 0x0, x57, x54); var x60: u32 = undefined; var x61: u1 = undefined; fiatSecp256k1AddcarryxU32(&x60, &x61, x59, x55, x52); var x62: u32 = undefined; var x63: u1 = undefined; fiatSecp256k1AddcarryxU32(&x62, &x63, x61, x53, x50); var x64: u32 = undefined; var x65: u1 = undefined; fiatSecp256k1AddcarryxU32(&x64, &x65, x63, x51, x48); var x66: u32 = undefined; var x67: u1 = undefined; fiatSecp256k1AddcarryxU32(&x66, &x67, x65, x49, x46); var x68: u32 = undefined; var x69: u1 = undefined; fiatSecp256k1AddcarryxU32(&x68, &x69, x67, x47, x44); var x70: u32 = undefined; var x71: u1 = undefined; fiatSecp256k1AddcarryxU32(&x70, &x71, x69, x45, x42); const x72: u32 = (@intCast(u32, x71) + x43); var x73: u32 = undefined; var x74: u1 = undefined; fiatSecp256k1AddcarryxU32(&x73, &x74, 0x0, x23, x56); var x75: u32 = undefined; var x76: u1 = undefined; fiatSecp256k1AddcarryxU32(&x75, &x76, x74, x25, x58); var x77: u32 = undefined; var x78: u1 = undefined; fiatSecp256k1AddcarryxU32(&x77, &x78, x76, x27, x60); var x79: u32 = undefined; var x80: u1 = undefined; fiatSecp256k1AddcarryxU32(&x79, &x80, x78, x29, x62); var x81: u32 = undefined; var x82: u1 = undefined; fiatSecp256k1AddcarryxU32(&x81, &x82, x80, x31, x64); var x83: u32 = undefined; var x84: u1 = undefined; fiatSecp256k1AddcarryxU32(&x83, &x84, x82, x33, x66); var x85: u32 = undefined; var x86: u1 = undefined; fiatSecp256k1AddcarryxU32(&x85, &x86, x84, x35, x68); var x87: u32 = undefined; var x88: u1 = undefined; fiatSecp256k1AddcarryxU32(&x87, &x88, x86, x37, x70); var x89: u32 = undefined; var x90: u1 = undefined; fiatSecp256k1AddcarryxU32(&x89, &x90, x88, x39, x72); var x91: u32 = undefined; var x92: u32 = undefined; fiatSecp256k1MulxU32(&x91, &x92, x1, (arg2[7])); var x93: u32 = undefined; var x94: u32 = undefined; fiatSecp256k1MulxU32(&x93, &x94, x1, (arg2[6])); var x95: u32 = undefined; var x96: u32 = undefined; fiatSecp256k1MulxU32(&x95, &x96, x1, (arg2[5])); var x97: u32 = undefined; var x98: u32 = undefined; fiatSecp256k1MulxU32(&x97, &x98, x1, (arg2[4])); var x99: u32 = undefined; var x100: u32 = undefined; fiatSecp256k1MulxU32(&x99, &x100, x1, (arg2[3])); var x101: u32 = undefined; var x102: u32 = undefined; fiatSecp256k1MulxU32(&x101, &x102, x1, (arg2[2])); var x103: u32 = undefined; var x104: u32 = undefined; fiatSecp256k1MulxU32(&x103, &x104, x1, (arg2[1])); var x105: u32 = undefined; var x106: u32 = undefined; fiatSecp256k1MulxU32(&x105, &x106, x1, (arg2[0])); var x107: u32 = undefined; var x108: u1 = undefined; fiatSecp256k1AddcarryxU32(&x107, &x108, 0x0, x106, x103); var x109: u32 = undefined; var x110: u1 = undefined; fiatSecp256k1AddcarryxU32(&x109, &x110, x108, x104, x101); var x111: u32 = undefined; var x112: u1 = undefined; fiatSecp256k1AddcarryxU32(&x111, &x112, x110, x102, x99); var x113: u32 = undefined; var x114: u1 = undefined; fiatSecp256k1AddcarryxU32(&x113, &x114, x112, x100, x97); var x115: u32 = undefined; var x116: u1 = undefined; fiatSecp256k1AddcarryxU32(&x115, &x116, x114, x98, x95); var x117: u32 = undefined; var x118: u1 = undefined; fiatSecp256k1AddcarryxU32(&x117, &x118, x116, x96, x93); var x119: u32 = undefined; var x120: u1 = undefined; fiatSecp256k1AddcarryxU32(&x119, &x120, x118, x94, x91); const x121: u32 = (@intCast(u32, x120) + x92); var x122: u32 = undefined; var x123: u1 = undefined; fiatSecp256k1AddcarryxU32(&x122, &x123, 0x0, x75, x105); var x124: u32 = undefined; var x125: u1 = undefined; fiatSecp256k1AddcarryxU32(&x124, &x125, x123, x77, x107); var x126: u32 = undefined; var x127: u1 = undefined; fiatSecp256k1AddcarryxU32(&x126, &x127, x125, x79, x109); var x128: u32 = undefined; var x129: u1 = undefined; fiatSecp256k1AddcarryxU32(&x128, &x129, x127, x81, x111); var x130: u32 = undefined; var x131: u1 = undefined; fiatSecp256k1AddcarryxU32(&x130, &x131, x129, x83, x113); var x132: u32 = undefined; var x133: u1 = undefined; fiatSecp256k1AddcarryxU32(&x132, &x133, x131, x85, x115); var x134: u32 = undefined; var x135: u1 = undefined; fiatSecp256k1AddcarryxU32(&x134, &x135, x133, x87, x117); var x136: u32 = undefined; var x137: u1 = undefined; fiatSecp256k1AddcarryxU32(&x136, &x137, x135, x89, x119); var x138: u32 = undefined; var x139: u1 = undefined; fiatSecp256k1AddcarryxU32(&x138, &x139, x137, @intCast(u32, x90), x121); var x140: u32 = undefined; var x141: u32 = undefined; fiatSecp256k1MulxU32(&x140, &x141, x122, 0xd2253531); var x142: u32 = undefined; var x143: u32 = undefined; fiatSecp256k1MulxU32(&x142, &x143, x140, 0xffffffff); var x144: u32 = undefined; var x145: u32 = undefined; fiatSecp256k1MulxU32(&x144, &x145, x140, 0xffffffff); var x146: u32 = undefined; var x147: u32 = undefined; fiatSecp256k1MulxU32(&x146, &x147, x140, 0xffffffff); var x148: u32 = undefined; var x149: u32 = undefined; fiatSecp256k1MulxU32(&x148, &x149, x140, 0xffffffff); var x150: u32 = undefined; var x151: u32 = undefined; fiatSecp256k1MulxU32(&x150, &x151, x140, 0xffffffff); var x152: u32 = undefined; var x153: u32 = undefined; fiatSecp256k1MulxU32(&x152, &x153, x140, 0xffffffff); var x154: u32 = undefined; var x155: u32 = undefined; fiatSecp256k1MulxU32(&x154, &x155, x140, 0xfffffffe); var x156: u32 = undefined; var x157: u32 = undefined; fiatSecp256k1MulxU32(&x156, &x157, x140, 0xfffffc2f); var x158: u32 = undefined; var x159: u1 = undefined; fiatSecp256k1AddcarryxU32(&x158, &x159, 0x0, x157, x154); var x160: u32 = undefined; var x161: u1 = undefined; fiatSecp256k1AddcarryxU32(&x160, &x161, x159, x155, x152); var x162: u32 = undefined; var x163: u1 = undefined; fiatSecp256k1AddcarryxU32(&x162, &x163, x161, x153, x150); var x164: u32 = undefined; var x165: u1 = undefined; fiatSecp256k1AddcarryxU32(&x164, &x165, x163, x151, x148); var x166: u32 = undefined; var x167: u1 = undefined; fiatSecp256k1AddcarryxU32(&x166, &x167, x165, x149, x146); var x168: u32 = undefined; var x169: u1 = undefined; fiatSecp256k1AddcarryxU32(&x168, &x169, x167, x147, x144); var x170: u32 = undefined; var x171: u1 = undefined; fiatSecp256k1AddcarryxU32(&x170, &x171, x169, x145, x142); const x172: u32 = (@intCast(u32, x171) + x143); var x173: u32 = undefined; var x174: u1 = undefined; fiatSecp256k1AddcarryxU32(&x173, &x174, 0x0, x122, x156); var x175: u32 = undefined; var x176: u1 = undefined; fiatSecp256k1AddcarryxU32(&x175, &x176, x174, x124, x158); var x177: u32 = undefined; var x178: u1 = undefined; fiatSecp256k1AddcarryxU32(&x177, &x178, x176, x126, x160); var x179: u32 = undefined; var x180: u1 = undefined; fiatSecp256k1AddcarryxU32(&x179, &x180, x178, x128, x162); var x181: u32 = undefined; var x182: u1 = undefined; fiatSecp256k1AddcarryxU32(&x181, &x182, x180, x130, x164); var x183: u32 = undefined; var x184: u1 = undefined; fiatSecp256k1AddcarryxU32(&x183, &x184, x182, x132, x166); var x185: u32 = undefined; var x186: u1 = undefined; fiatSecp256k1AddcarryxU32(&x185, &x186, x184, x134, x168); var x187: u32 = undefined; var x188: u1 = undefined; fiatSecp256k1AddcarryxU32(&x187, &x188, x186, x136, x170); var x189: u32 = undefined; var x190: u1 = undefined; fiatSecp256k1AddcarryxU32(&x189, &x190, x188, x138, x172); const x191: u32 = (@intCast(u32, x190) + @intCast(u32, x139)); var x192: u32 = undefined; var x193: u32 = undefined; fiatSecp256k1MulxU32(&x192, &x193, x2, (arg2[7])); var x194: u32 = undefined; var x195: u32 = undefined; fiatSecp256k1MulxU32(&x194, &x195, x2, (arg2[6])); var x196: u32 = undefined; var x197: u32 = undefined; fiatSecp256k1MulxU32(&x196, &x197, x2, (arg2[5])); var x198: u32 = undefined; var x199: u32 = undefined; fiatSecp256k1MulxU32(&x198, &x199, x2, (arg2[4])); var x200: u32 = undefined; var x201: u32 = undefined; fiatSecp256k1MulxU32(&x200, &x201, x2, (arg2[3])); var x202: u32 = undefined; var x203: u32 = undefined; fiatSecp256k1MulxU32(&x202, &x203, x2, (arg2[2])); var x204: u32 = undefined; var x205: u32 = undefined; fiatSecp256k1MulxU32(&x204, &x205, x2, (arg2[1])); var x206: u32 = undefined; var x207: u32 = undefined; fiatSecp256k1MulxU32(&x206, &x207, x2, (arg2[0])); var x208: u32 = undefined; var x209: u1 = undefined; fiatSecp256k1AddcarryxU32(&x208, &x209, 0x0, x207, x204); var x210: u32 = undefined; var x211: u1 = undefined; fiatSecp256k1AddcarryxU32(&x210, &x211, x209, x205, x202); var x212: u32 = undefined; var x213: u1 = undefined; fiatSecp256k1AddcarryxU32(&x212, &x213, x211, x203, x200); var x214: u32 = undefined; var x215: u1 = undefined; fiatSecp256k1AddcarryxU32(&x214, &x215, x213, x201, x198); var x216: u32 = undefined; var x217: u1 = undefined; fiatSecp256k1AddcarryxU32(&x216, &x217, x215, x199, x196); var x218: u32 = undefined; var x219: u1 = undefined; fiatSecp256k1AddcarryxU32(&x218, &x219, x217, x197, x194); var x220: u32 = undefined; var x221: u1 = undefined; fiatSecp256k1AddcarryxU32(&x220, &x221, x219, x195, x192); const x222: u32 = (@intCast(u32, x221) + x193); var x223: u32 = undefined; var x224: u1 = undefined; fiatSecp256k1AddcarryxU32(&x223, &x224, 0x0, x175, x206); var x225: u32 = undefined; var x226: u1 = undefined; fiatSecp256k1AddcarryxU32(&x225, &x226, x224, x177, x208); var x227: u32 = undefined; var x228: u1 = undefined; fiatSecp256k1AddcarryxU32(&x227, &x228, x226, x179, x210); var x229: u32 = undefined; var x230: u1 = undefined; fiatSecp256k1AddcarryxU32(&x229, &x230, x228, x181, x212); var x231: u32 = undefined; var x232: u1 = undefined; fiatSecp256k1AddcarryxU32(&x231, &x232, x230, x183, x214); var x233: u32 = undefined; var x234: u1 = undefined; fiatSecp256k1AddcarryxU32(&x233, &x234, x232, x185, x216); var x235: u32 = undefined; var x236: u1 = undefined; fiatSecp256k1AddcarryxU32(&x235, &x236, x234, x187, x218); var x237: u32 = undefined; var x238: u1 = undefined; fiatSecp256k1AddcarryxU32(&x237, &x238, x236, x189, x220); var x239: u32 = undefined; var x240: u1 = undefined; fiatSecp256k1AddcarryxU32(&x239, &x240, x238, x191, x222); var x241: u32 = undefined; var x242: u32 = undefined; fiatSecp256k1MulxU32(&x241, &x242, x223, 0xd2253531); var x243: u32 = undefined; var x244: u32 = undefined; fiatSecp256k1MulxU32(&x243, &x244, x241, 0xffffffff); var x245: u32 = undefined; var x246: u32 = undefined; fiatSecp256k1MulxU32(&x245, &x246, x241, 0xffffffff); var x247: u32 = undefined; var x248: u32 = undefined; fiatSecp256k1MulxU32(&x247, &x248, x241, 0xffffffff); var x249: u32 = undefined; var x250: u32 = undefined; fiatSecp256k1MulxU32(&x249, &x250, x241, 0xffffffff); var x251: u32 = undefined; var x252: u32 = undefined; fiatSecp256k1MulxU32(&x251, &x252, x241, 0xffffffff); var x253: u32 = undefined; var x254: u32 = undefined; fiatSecp256k1MulxU32(&x253, &x254, x241, 0xffffffff); var x255: u32 = undefined; var x256: u32 = undefined; fiatSecp256k1MulxU32(&x255, &x256, x241, 0xfffffffe); var x257: u32 = undefined; var x258: u32 = undefined; fiatSecp256k1MulxU32(&x257, &x258, x241, 0xfffffc2f); var x259: u32 = undefined; var x260: u1 = undefined; fiatSecp256k1AddcarryxU32(&x259, &x260, 0x0, x258, x255); var x261: u32 = undefined; var x262: u1 = undefined; fiatSecp256k1AddcarryxU32(&x261, &x262, x260, x256, x253); var x263: u32 = undefined; var x264: u1 = undefined; fiatSecp256k1AddcarryxU32(&x263, &x264, x262, x254, x251); var x265: u32 = undefined; var x266: u1 = undefined; fiatSecp256k1AddcarryxU32(&x265, &x266, x264, x252, x249); var x267: u32 = undefined; var x268: u1 = undefined; fiatSecp256k1AddcarryxU32(&x267, &x268, x266, x250, x247); var x269: u32 = undefined; var x270: u1 = undefined; fiatSecp256k1AddcarryxU32(&x269, &x270, x268, x248, x245); var x271: u32 = undefined; var x272: u1 = undefined; fiatSecp256k1AddcarryxU32(&x271, &x272, x270, x246, x243); const x273: u32 = (@intCast(u32, x272) + x244); var x274: u32 = undefined; var x275: u1 = undefined; fiatSecp256k1AddcarryxU32(&x274, &x275, 0x0, x223, x257); var x276: u32 = undefined; var x277: u1 = undefined; fiatSecp256k1AddcarryxU32(&x276, &x277, x275, x225, x259); var x278: u32 = undefined; var x279: u1 = undefined; fiatSecp256k1AddcarryxU32(&x278, &x279, x277, x227, x261); var x280: u32 = undefined; var x281: u1 = undefined; fiatSecp256k1AddcarryxU32(&x280, &x281, x279, x229, x263); var x282: u32 = undefined; var x283: u1 = undefined; fiatSecp256k1AddcarryxU32(&x282, &x283, x281, x231, x265); var x284: u32 = undefined; var x285: u1 = undefined; fiatSecp256k1AddcarryxU32(&x284, &x285, x283, x233, x267); var x286: u32 = undefined; var x287: u1 = undefined; fiatSecp256k1AddcarryxU32(&x286, &x287, x285, x235, x269); var x288: u32 = undefined; var x289: u1 = undefined; fiatSecp256k1AddcarryxU32(&x288, &x289, x287, x237, x271); var x290: u32 = undefined; var x291: u1 = undefined; fiatSecp256k1AddcarryxU32(&x290, &x291, x289, x239, x273); const x292: u32 = (@intCast(u32, x291) + @intCast(u32, x240)); var x293: u32 = undefined; var x294: u32 = undefined; fiatSecp256k1MulxU32(&x293, &x294, x3, (arg2[7])); var x295: u32 = undefined; var x296: u32 = undefined; fiatSecp256k1MulxU32(&x295, &x296, x3, (arg2[6])); var x297: u32 = undefined; var x298: u32 = undefined; fiatSecp256k1MulxU32(&x297, &x298, x3, (arg2[5])); var x299: u32 = undefined; var x300: u32 = undefined; fiatSecp256k1MulxU32(&x299, &x300, x3, (arg2[4])); var x301: u32 = undefined; var x302: u32 = undefined; fiatSecp256k1MulxU32(&x301, &x302, x3, (arg2[3])); var x303: u32 = undefined; var x304: u32 = undefined; fiatSecp256k1MulxU32(&x303, &x304, x3, (arg2[2])); var x305: u32 = undefined; var x306: u32 = undefined; fiatSecp256k1MulxU32(&x305, &x306, x3, (arg2[1])); var x307: u32 = undefined; var x308: u32 = undefined; fiatSecp256k1MulxU32(&x307, &x308, x3, (arg2[0])); var x309: u32 = undefined; var x310: u1 = undefined; fiatSecp256k1AddcarryxU32(&x309, &x310, 0x0, x308, x305); var x311: u32 = undefined; var x312: u1 = undefined; fiatSecp256k1AddcarryxU32(&x311, &x312, x310, x306, x303); var x313: u32 = undefined; var x314: u1 = undefined; fiatSecp256k1AddcarryxU32(&x313, &x314, x312, x304, x301); var x315: u32 = undefined; var x316: u1 = undefined; fiatSecp256k1AddcarryxU32(&x315, &x316, x314, x302, x299); var x317: u32 = undefined; var x318: u1 = undefined; fiatSecp256k1AddcarryxU32(&x317, &x318, x316, x300, x297); var x319: u32 = undefined; var x320: u1 = undefined; fiatSecp256k1AddcarryxU32(&x319, &x320, x318, x298, x295); var x321: u32 = undefined; var x322: u1 = undefined; fiatSecp256k1AddcarryxU32(&x321, &x322, x320, x296, x293); const x323: u32 = (@intCast(u32, x322) + x294); var x324: u32 = undefined; var x325: u1 = undefined; fiatSecp256k1AddcarryxU32(&x324, &x325, 0x0, x276, x307); var x326: u32 = undefined; var x327: u1 = undefined; fiatSecp256k1AddcarryxU32(&x326, &x327, x325, x278, x309); var x328: u32 = undefined; var x329: u1 = undefined; fiatSecp256k1AddcarryxU32(&x328, &x329, x327, x280, x311); var x330: u32 = undefined; var x331: u1 = undefined; fiatSecp256k1AddcarryxU32(&x330, &x331, x329, x282, x313); var x332: u32 = undefined; var x333: u1 = undefined; fiatSecp256k1AddcarryxU32(&x332, &x333, x331, x284, x315); var x334: u32 = undefined; var x335: u1 = undefined; fiatSecp256k1AddcarryxU32(&x334, &x335, x333, x286, x317); var x336: u32 = undefined; var x337: u1 = undefined; fiatSecp256k1AddcarryxU32(&x336, &x337, x335, x288, x319); var x338: u32 = undefined; var x339: u1 = undefined; fiatSecp256k1AddcarryxU32(&x338, &x339, x337, x290, x321); var x340: u32 = undefined; var x341: u1 = undefined; fiatSecp256k1AddcarryxU32(&x340, &x341, x339, x292, x323); var x342: u32 = undefined; var x343: u32 = undefined; fiatSecp256k1MulxU32(&x342, &x343, x324, 0xd2253531); var x344: u32 = undefined; var x345: u32 = undefined; fiatSecp256k1MulxU32(&x344, &x345, x342, 0xffffffff); var x346: u32 = undefined; var x347: u32 = undefined; fiatSecp256k1MulxU32(&x346, &x347, x342, 0xffffffff); var x348: u32 = undefined; var x349: u32 = undefined; fiatSecp256k1MulxU32(&x348, &x349, x342, 0xffffffff); var x350: u32 = undefined; var x351: u32 = undefined; fiatSecp256k1MulxU32(&x350, &x351, x342, 0xffffffff); var x352: u32 = undefined; var x353: u32 = undefined; fiatSecp256k1MulxU32(&x352, &x353, x342, 0xffffffff); var x354: u32 = undefined; var x355: u32 = undefined; fiatSecp256k1MulxU32(&x354, &x355, x342, 0xffffffff); var x356: u32 = undefined; var x357: u32 = undefined; fiatSecp256k1MulxU32(&x356, &x357, x342, 0xfffffffe); var x358: u32 = undefined; var x359: u32 = undefined; fiatSecp256k1MulxU32(&x358, &x359, x342, 0xfffffc2f); var x360: u32 = undefined; var x361: u1 = undefined; fiatSecp256k1AddcarryxU32(&x360, &x361, 0x0, x359, x356); var x362: u32 = undefined; var x363: u1 = undefined; fiatSecp256k1AddcarryxU32(&x362, &x363, x361, x357, x354); var x364: u32 = undefined; var x365: u1 = undefined; fiatSecp256k1AddcarryxU32(&x364, &x365, x363, x355, x352); var x366: u32 = undefined; var x367: u1 = undefined; fiatSecp256k1AddcarryxU32(&x366, &x367, x365, x353, x350); var x368: u32 = undefined; var x369: u1 = undefined; fiatSecp256k1AddcarryxU32(&x368, &x369, x367, x351, x348); var x370: u32 = undefined; var x371: u1 = undefined; fiatSecp256k1AddcarryxU32(&x370, &x371, x369, x349, x346); var x372: u32 = undefined; var x373: u1 = undefined; fiatSecp256k1AddcarryxU32(&x372, &x373, x371, x347, x344); const x374: u32 = (@intCast(u32, x373) + x345); var x375: u32 = undefined; var x376: u1 = undefined; fiatSecp256k1AddcarryxU32(&x375, &x376, 0x0, x324, x358); var x377: u32 = undefined; var x378: u1 = undefined; fiatSecp256k1AddcarryxU32(&x377, &x378, x376, x326, x360); var x379: u32 = undefined; var x380: u1 = undefined; fiatSecp256k1AddcarryxU32(&x379, &x380, x378, x328, x362); var x381: u32 = undefined; var x382: u1 = undefined; fiatSecp256k1AddcarryxU32(&x381, &x382, x380, x330, x364); var x383: u32 = undefined; var x384: u1 = undefined; fiatSecp256k1AddcarryxU32(&x383, &x384, x382, x332, x366); var x385: u32 = undefined; var x386: u1 = undefined; fiatSecp256k1AddcarryxU32(&x385, &x386, x384, x334, x368); var x387: u32 = undefined; var x388: u1 = undefined; fiatSecp256k1AddcarryxU32(&x387, &x388, x386, x336, x370); var x389: u32 = undefined; var x390: u1 = undefined; fiatSecp256k1AddcarryxU32(&x389, &x390, x388, x338, x372); var x391: u32 = undefined; var x392: u1 = undefined; fiatSecp256k1AddcarryxU32(&x391, &x392, x390, x340, x374); const x393: u32 = (@intCast(u32, x392) + @intCast(u32, x341)); var x394: u32 = undefined; var x395: u32 = undefined; fiatSecp256k1MulxU32(&x394, &x395, x4, (arg2[7])); var x396: u32 = undefined; var x397: u32 = undefined; fiatSecp256k1MulxU32(&x396, &x397, x4, (arg2[6])); var x398: u32 = undefined; var x399: u32 = undefined; fiatSecp256k1MulxU32(&x398, &x399, x4, (arg2[5])); var x400: u32 = undefined; var x401: u32 = undefined; fiatSecp256k1MulxU32(&x400, &x401, x4, (arg2[4])); var x402: u32 = undefined; var x403: u32 = undefined; fiatSecp256k1MulxU32(&x402, &x403, x4, (arg2[3])); var x404: u32 = undefined; var x405: u32 = undefined; fiatSecp256k1MulxU32(&x404, &x405, x4, (arg2[2])); var x406: u32 = undefined; var x407: u32 = undefined; fiatSecp256k1MulxU32(&x406, &x407, x4, (arg2[1])); var x408: u32 = undefined; var x409: u32 = undefined; fiatSecp256k1MulxU32(&x408, &x409, x4, (arg2[0])); var x410: u32 = undefined; var x411: u1 = undefined; fiatSecp256k1AddcarryxU32(&x410, &x411, 0x0, x409, x406); var x412: u32 = undefined; var x413: u1 = undefined; fiatSecp256k1AddcarryxU32(&x412, &x413, x411, x407, x404); var x414: u32 = undefined; var x415: u1 = undefined; fiatSecp256k1AddcarryxU32(&x414, &x415, x413, x405, x402); var x416: u32 = undefined; var x417: u1 = undefined; fiatSecp256k1AddcarryxU32(&x416, &x417, x415, x403, x400); var x418: u32 = undefined; var x419: u1 = undefined; fiatSecp256k1AddcarryxU32(&x418, &x419, x417, x401, x398); var x420: u32 = undefined; var x421: u1 = undefined; fiatSecp256k1AddcarryxU32(&x420, &x421, x419, x399, x396); var x422: u32 = undefined; var x423: u1 = undefined; fiatSecp256k1AddcarryxU32(&x422, &x423, x421, x397, x394); const x424: u32 = (@intCast(u32, x423) + x395); var x425: u32 = undefined; var x426: u1 = undefined; fiatSecp256k1AddcarryxU32(&x425, &x426, 0x0, x377, x408); var x427: u32 = undefined; var x428: u1 = undefined; fiatSecp256k1AddcarryxU32(&x427, &x428, x426, x379, x410); var x429: u32 = undefined; var x430: u1 = undefined; fiatSecp256k1AddcarryxU32(&x429, &x430, x428, x381, x412); var x431: u32 = undefined; var x432: u1 = undefined; fiatSecp256k1AddcarryxU32(&x431, &x432, x430, x383, x414); var x433: u32 = undefined; var x434: u1 = undefined; fiatSecp256k1AddcarryxU32(&x433, &x434, x432, x385, x416); var x435: u32 = undefined; var x436: u1 = undefined; fiatSecp256k1AddcarryxU32(&x435, &x436, x434, x387, x418); var x437: u32 = undefined; var x438: u1 = undefined; fiatSecp256k1AddcarryxU32(&x437, &x438, x436, x389, x420); var x439: u32 = undefined; var x440: u1 = undefined; fiatSecp256k1AddcarryxU32(&x439, &x440, x438, x391, x422); var x441: u32 = undefined; var x442: u1 = undefined; fiatSecp256k1AddcarryxU32(&x441, &x442, x440, x393, x424); var x443: u32 = undefined; var x444: u32 = undefined; fiatSecp256k1MulxU32(&x443, &x444, x425, 0xd2253531); var x445: u32 = undefined; var x446: u32 = undefined; fiatSecp256k1MulxU32(&x445, &x446, x443, 0xffffffff); var x447: u32 = undefined; var x448: u32 = undefined; fiatSecp256k1MulxU32(&x447, &x448, x443, 0xffffffff); var x449: u32 = undefined; var x450: u32 = undefined; fiatSecp256k1MulxU32(&x449, &x450, x443, 0xffffffff); var x451: u32 = undefined; var x452: u32 = undefined; fiatSecp256k1MulxU32(&x451, &x452, x443, 0xffffffff); var x453: u32 = undefined; var x454: u32 = undefined; fiatSecp256k1MulxU32(&x453, &x454, x443, 0xffffffff); var x455: u32 = undefined; var x456: u32 = undefined; fiatSecp256k1MulxU32(&x455, &x456, x443, 0xffffffff); var x457: u32 = undefined; var x458: u32 = undefined; fiatSecp256k1MulxU32(&x457, &x458, x443, 0xfffffffe); var x459: u32 = undefined; var x460: u32 = undefined; fiatSecp256k1MulxU32(&x459, &x460, x443, 0xfffffc2f); var x461: u32 = undefined; var x462: u1 = undefined; fiatSecp256k1AddcarryxU32(&x461, &x462, 0x0, x460, x457); var x463: u32 = undefined; var x464: u1 = undefined; fiatSecp256k1AddcarryxU32(&x463, &x464, x462, x458, x455); var x465: u32 = undefined; var x466: u1 = undefined; fiatSecp256k1AddcarryxU32(&x465, &x466, x464, x456, x453); var x467: u32 = undefined; var x468: u1 = undefined; fiatSecp256k1AddcarryxU32(&x467, &x468, x466, x454, x451); var x469: u32 = undefined; var x470: u1 = undefined; fiatSecp256k1AddcarryxU32(&x469, &x470, x468, x452, x449); var x471: u32 = undefined; var x472: u1 = undefined; fiatSecp256k1AddcarryxU32(&x471, &x472, x470, x450, x447); var x473: u32 = undefined; var x474: u1 = undefined; fiatSecp256k1AddcarryxU32(&x473, &x474, x472, x448, x445); const x475: u32 = (@intCast(u32, x474) + x446); var x476: u32 = undefined; var x477: u1 = undefined; fiatSecp256k1AddcarryxU32(&x476, &x477, 0x0, x425, x459); var x478: u32 = undefined; var x479: u1 = undefined; fiatSecp256k1AddcarryxU32(&x478, &x479, x477, x427, x461); var x480: u32 = undefined; var x481: u1 = undefined; fiatSecp256k1AddcarryxU32(&x480, &x481, x479, x429, x463); var x482: u32 = undefined; var x483: u1 = undefined; fiatSecp256k1AddcarryxU32(&x482, &x483, x481, x431, x465); var x484: u32 = undefined; var x485: u1 = undefined; fiatSecp256k1AddcarryxU32(&x484, &x485, x483, x433, x467); var x486: u32 = undefined; var x487: u1 = undefined; fiatSecp256k1AddcarryxU32(&x486, &x487, x485, x435, x469); var x488: u32 = undefined; var x489: u1 = undefined; fiatSecp256k1AddcarryxU32(&x488, &x489, x487, x437, x471); var x490: u32 = undefined; var x491: u1 = undefined; fiatSecp256k1AddcarryxU32(&x490, &x491, x489, x439, x473); var x492: u32 = undefined; var x493: u1 = undefined; fiatSecp256k1AddcarryxU32(&x492, &x493, x491, x441, x475); const x494: u32 = (@intCast(u32, x493) + @intCast(u32, x442)); var x495: u32 = undefined; var x496: u32 = undefined; fiatSecp256k1MulxU32(&x495, &x496, x5, (arg2[7])); var x497: u32 = undefined; var x498: u32 = undefined; fiatSecp256k1MulxU32(&x497, &x498, x5, (arg2[6])); var x499: u32 = undefined; var x500: u32 = undefined; fiatSecp256k1MulxU32(&x499, &x500, x5, (arg2[5])); var x501: u32 = undefined; var x502: u32 = undefined; fiatSecp256k1MulxU32(&x501, &x502, x5, (arg2[4])); var x503: u32 = undefined; var x504: u32 = undefined; fiatSecp256k1MulxU32(&x503, &x504, x5, (arg2[3])); var x505: u32 = undefined; var x506: u32 = undefined; fiatSecp256k1MulxU32(&x505, &x506, x5, (arg2[2])); var x507: u32 = undefined; var x508: u32 = undefined; fiatSecp256k1MulxU32(&x507, &x508, x5, (arg2[1])); var x509: u32 = undefined; var x510: u32 = undefined; fiatSecp256k1MulxU32(&x509, &x510, x5, (arg2[0])); var x511: u32 = undefined; var x512: u1 = undefined; fiatSecp256k1AddcarryxU32(&x511, &x512, 0x0, x510, x507); var x513: u32 = undefined; var x514: u1 = undefined; fiatSecp256k1AddcarryxU32(&x513, &x514, x512, x508, x505); var x515: u32 = undefined; var x516: u1 = undefined; fiatSecp256k1AddcarryxU32(&x515, &x516, x514, x506, x503); var x517: u32 = undefined; var x518: u1 = undefined; fiatSecp256k1AddcarryxU32(&x517, &x518, x516, x504, x501); var x519: u32 = undefined; var x520: u1 = undefined; fiatSecp256k1AddcarryxU32(&x519, &x520, x518, x502, x499); var x521: u32 = undefined; var x522: u1 = undefined; fiatSecp256k1AddcarryxU32(&x521, &x522, x520, x500, x497); var x523: u32 = undefined; var x524: u1 = undefined; fiatSecp256k1AddcarryxU32(&x523, &x524, x522, x498, x495); const x525: u32 = (@intCast(u32, x524) + x496); var x526: u32 = undefined; var x527: u1 = undefined; fiatSecp256k1AddcarryxU32(&x526, &x527, 0x0, x478, x509); var x528: u32 = undefined; var x529: u1 = undefined; fiatSecp256k1AddcarryxU32(&x528, &x529, x527, x480, x511); var x530: u32 = undefined; var x531: u1 = undefined; fiatSecp256k1AddcarryxU32(&x530, &x531, x529, x482, x513); var x532: u32 = undefined; var x533: u1 = undefined; fiatSecp256k1AddcarryxU32(&x532, &x533, x531, x484, x515); var x534: u32 = undefined; var x535: u1 = undefined; fiatSecp256k1AddcarryxU32(&x534, &x535, x533, x486, x517); var x536: u32 = undefined; var x537: u1 = undefined; fiatSecp256k1AddcarryxU32(&x536, &x537, x535, x488, x519); var x538: u32 = undefined; var x539: u1 = undefined; fiatSecp256k1AddcarryxU32(&x538, &x539, x537, x490, x521); var x540: u32 = undefined; var x541: u1 = undefined; fiatSecp256k1AddcarryxU32(&x540, &x541, x539, x492, x523); var x542: u32 = undefined; var x543: u1 = undefined; fiatSecp256k1AddcarryxU32(&x542, &x543, x541, x494, x525); var x544: u32 = undefined; var x545: u32 = undefined; fiatSecp256k1MulxU32(&x544, &x545, x526, 0xd2253531); var x546: u32 = undefined; var x547: u32 = undefined; fiatSecp256k1MulxU32(&x546, &x547, x544, 0xffffffff); var x548: u32 = undefined; var x549: u32 = undefined; fiatSecp256k1MulxU32(&x548, &x549, x544, 0xffffffff); var x550: u32 = undefined; var x551: u32 = undefined; fiatSecp256k1MulxU32(&x550, &x551, x544, 0xffffffff); var x552: u32 = undefined; var x553: u32 = undefined; fiatSecp256k1MulxU32(&x552, &x553, x544, 0xffffffff); var x554: u32 = undefined; var x555: u32 = undefined; fiatSecp256k1MulxU32(&x554, &x555, x544, 0xffffffff); var x556: u32 = undefined; var x557: u32 = undefined; fiatSecp256k1MulxU32(&x556, &x557, x544, 0xffffffff); var x558: u32 = undefined; var x559: u32 = undefined; fiatSecp256k1MulxU32(&x558, &x559, x544, 0xfffffffe); var x560: u32 = undefined; var x561: u32 = undefined; fiatSecp256k1MulxU32(&x560, &x561, x544, 0xfffffc2f); var x562: u32 = undefined; var x563: u1 = undefined; fiatSecp256k1AddcarryxU32(&x562, &x563, 0x0, x561, x558); var x564: u32 = undefined; var x565: u1 = undefined; fiatSecp256k1AddcarryxU32(&x564, &x565, x563, x559, x556); var x566: u32 = undefined; var x567: u1 = undefined; fiatSecp256k1AddcarryxU32(&x566, &x567, x565, x557, x554); var x568: u32 = undefined; var x569: u1 = undefined; fiatSecp256k1AddcarryxU32(&x568, &x569, x567, x555, x552); var x570: u32 = undefined; var x571: u1 = undefined; fiatSecp256k1AddcarryxU32(&x570, &x571, x569, x553, x550); var x572: u32 = undefined; var x573: u1 = undefined; fiatSecp256k1AddcarryxU32(&x572, &x573, x571, x551, x548); var x574: u32 = undefined; var x575: u1 = undefined; fiatSecp256k1AddcarryxU32(&x574, &x575, x573, x549, x546); const x576: u32 = (@intCast(u32, x575) + x547); var x577: u32 = undefined; var x578: u1 = undefined; fiatSecp256k1AddcarryxU32(&x577, &x578, 0x0, x526, x560); var x579: u32 = undefined; var x580: u1 = undefined; fiatSecp256k1AddcarryxU32(&x579, &x580, x578, x528, x562); var x581: u32 = undefined; var x582: u1 = undefined; fiatSecp256k1AddcarryxU32(&x581, &x582, x580, x530, x564); var x583: u32 = undefined; var x584: u1 = undefined; fiatSecp256k1AddcarryxU32(&x583, &x584, x582, x532, x566); var x585: u32 = undefined; var x586: u1 = undefined; fiatSecp256k1AddcarryxU32(&x585, &x586, x584, x534, x568); var x587: u32 = undefined; var x588: u1 = undefined; fiatSecp256k1AddcarryxU32(&x587, &x588, x586, x536, x570); var x589: u32 = undefined; var x590: u1 = undefined; fiatSecp256k1AddcarryxU32(&x589, &x590, x588, x538, x572); var x591: u32 = undefined; var x592: u1 = undefined; fiatSecp256k1AddcarryxU32(&x591, &x592, x590, x540, x574); var x593: u32 = undefined; var x594: u1 = undefined; fiatSecp256k1AddcarryxU32(&x593, &x594, x592, x542, x576); const x595: u32 = (@intCast(u32, x594) + @intCast(u32, x543)); var x596: u32 = undefined; var x597: u32 = undefined; fiatSecp256k1MulxU32(&x596, &x597, x6, (arg2[7])); var x598: u32 = undefined; var x599: u32 = undefined; fiatSecp256k1MulxU32(&x598, &x599, x6, (arg2[6])); var x600: u32 = undefined; var x601: u32 = undefined; fiatSecp256k1MulxU32(&x600, &x601, x6, (arg2[5])); var x602: u32 = undefined; var x603: u32 = undefined; fiatSecp256k1MulxU32(&x602, &x603, x6, (arg2[4])); var x604: u32 = undefined; var x605: u32 = undefined; fiatSecp256k1MulxU32(&x604, &x605, x6, (arg2[3])); var x606: u32 = undefined; var x607: u32 = undefined; fiatSecp256k1MulxU32(&x606, &x607, x6, (arg2[2])); var x608: u32 = undefined; var x609: u32 = undefined; fiatSecp256k1MulxU32(&x608, &x609, x6, (arg2[1])); var x610: u32 = undefined; var x611: u32 = undefined; fiatSecp256k1MulxU32(&x610, &x611, x6, (arg2[0])); var x612: u32 = undefined; var x613: u1 = undefined; fiatSecp256k1AddcarryxU32(&x612, &x613, 0x0, x611, x608); var x614: u32 = undefined; var x615: u1 = undefined; fiatSecp256k1AddcarryxU32(&x614, &x615, x613, x609, x606); var x616: u32 = undefined; var x617: u1 = undefined; fiatSecp256k1AddcarryxU32(&x616, &x617, x615, x607, x604); var x618: u32 = undefined; var x619: u1 = undefined; fiatSecp256k1AddcarryxU32(&x618, &x619, x617, x605, x602); var x620: u32 = undefined; var x621: u1 = undefined; fiatSecp256k1AddcarryxU32(&x620, &x621, x619, x603, x600); var x622: u32 = undefined; var x623: u1 = undefined; fiatSecp256k1AddcarryxU32(&x622, &x623, x621, x601, x598); var x624: u32 = undefined; var x625: u1 = undefined; fiatSecp256k1AddcarryxU32(&x624, &x625, x623, x599, x596); const x626: u32 = (@intCast(u32, x625) + x597); var x627: u32 = undefined; var x628: u1 = undefined; fiatSecp256k1AddcarryxU32(&x627, &x628, 0x0, x579, x610); var x629: u32 = undefined; var x630: u1 = undefined; fiatSecp256k1AddcarryxU32(&x629, &x630, x628, x581, x612); var x631: u32 = undefined; var x632: u1 = undefined; fiatSecp256k1AddcarryxU32(&x631, &x632, x630, x583, x614); var x633: u32 = undefined; var x634: u1 = undefined; fiatSecp256k1AddcarryxU32(&x633, &x634, x632, x585, x616); var x635: u32 = undefined; var x636: u1 = undefined; fiatSecp256k1AddcarryxU32(&x635, &x636, x634, x587, x618); var x637: u32 = undefined; var x638: u1 = undefined; fiatSecp256k1AddcarryxU32(&x637, &x638, x636, x589, x620); var x639: u32 = undefined; var x640: u1 = undefined; fiatSecp256k1AddcarryxU32(&x639, &x640, x638, x591, x622); var x641: u32 = undefined; var x642: u1 = undefined; fiatSecp256k1AddcarryxU32(&x641, &x642, x640, x593, x624); var x643: u32 = undefined; var x644: u1 = undefined; fiatSecp256k1AddcarryxU32(&x643, &x644, x642, x595, x626); var x645: u32 = undefined; var x646: u32 = undefined; fiatSecp256k1MulxU32(&x645, &x646, x627, 0xd2253531); var x647: u32 = undefined; var x648: u32 = undefined; fiatSecp256k1MulxU32(&x647, &x648, x645, 0xffffffff); var x649: u32 = undefined; var x650: u32 = undefined; fiatSecp256k1MulxU32(&x649, &x650, x645, 0xffffffff); var x651: u32 = undefined; var x652: u32 = undefined; fiatSecp256k1MulxU32(&x651, &x652, x645, 0xffffffff); var x653: u32 = undefined; var x654: u32 = undefined; fiatSecp256k1MulxU32(&x653, &x654, x645, 0xffffffff); var x655: u32 = undefined; var x656: u32 = undefined; fiatSecp256k1MulxU32(&x655, &x656, x645, 0xffffffff); var x657: u32 = undefined; var x658: u32 = undefined; fiatSecp256k1MulxU32(&x657, &x658, x645, 0xffffffff); var x659: u32 = undefined; var x660: u32 = undefined; fiatSecp256k1MulxU32(&x659, &x660, x645, 0xfffffffe); var x661: u32 = undefined; var x662: u32 = undefined; fiatSecp256k1MulxU32(&x661, &x662, x645, 0xfffffc2f); var x663: u32 = undefined; var x664: u1 = undefined; fiatSecp256k1AddcarryxU32(&x663, &x664, 0x0, x662, x659); var x665: u32 = undefined; var x666: u1 = undefined; fiatSecp256k1AddcarryxU32(&x665, &x666, x664, x660, x657); var x667: u32 = undefined; var x668: u1 = undefined; fiatSecp256k1AddcarryxU32(&x667, &x668, x666, x658, x655); var x669: u32 = undefined; var x670: u1 = undefined; fiatSecp256k1AddcarryxU32(&x669, &x670, x668, x656, x653); var x671: u32 = undefined; var x672: u1 = undefined; fiatSecp256k1AddcarryxU32(&x671, &x672, x670, x654, x651); var x673: u32 = undefined; var x674: u1 = undefined; fiatSecp256k1AddcarryxU32(&x673, &x674, x672, x652, x649); var x675: u32 = undefined; var x676: u1 = undefined; fiatSecp256k1AddcarryxU32(&x675, &x676, x674, x650, x647); const x677: u32 = (@intCast(u32, x676) + x648); var x678: u32 = undefined; var x679: u1 = undefined; fiatSecp256k1AddcarryxU32(&x678, &x679, 0x0, x627, x661); var x680: u32 = undefined; var x681: u1 = undefined; fiatSecp256k1AddcarryxU32(&x680, &x681, x679, x629, x663); var x682: u32 = undefined; var x683: u1 = undefined; fiatSecp256k1AddcarryxU32(&x682, &x683, x681, x631, x665); var x684: u32 = undefined; var x685: u1 = undefined; fiatSecp256k1AddcarryxU32(&x684, &x685, x683, x633, x667); var x686: u32 = undefined; var x687: u1 = undefined; fiatSecp256k1AddcarryxU32(&x686, &x687, x685, x635, x669); var x688: u32 = undefined; var x689: u1 = undefined; fiatSecp256k1AddcarryxU32(&x688, &x689, x687, x637, x671); var x690: u32 = undefined; var x691: u1 = undefined; fiatSecp256k1AddcarryxU32(&x690, &x691, x689, x639, x673); var x692: u32 = undefined; var x693: u1 = undefined; fiatSecp256k1AddcarryxU32(&x692, &x693, x691, x641, x675); var x694: u32 = undefined; var x695: u1 = undefined; fiatSecp256k1AddcarryxU32(&x694, &x695, x693, x643, x677); const x696: u32 = (@intCast(u32, x695) + @intCast(u32, x644)); var x697: u32 = undefined; var x698: u32 = undefined; fiatSecp256k1MulxU32(&x697, &x698, x7, (arg2[7])); var x699: u32 = undefined; var x700: u32 = undefined; fiatSecp256k1MulxU32(&x699, &x700, x7, (arg2[6])); var x701: u32 = undefined; var x702: u32 = undefined; fiatSecp256k1MulxU32(&x701, &x702, x7, (arg2[5])); var x703: u32 = undefined; var x704: u32 = undefined; fiatSecp256k1MulxU32(&x703, &x704, x7, (arg2[4])); var x705: u32 = undefined; var x706: u32 = undefined; fiatSecp256k1MulxU32(&x705, &x706, x7, (arg2[3])); var x707: u32 = undefined; var x708: u32 = undefined; fiatSecp256k1MulxU32(&x707, &x708, x7, (arg2[2])); var x709: u32 = undefined; var x710: u32 = undefined; fiatSecp256k1MulxU32(&x709, &x710, x7, (arg2[1])); var x711: u32 = undefined; var x712: u32 = undefined; fiatSecp256k1MulxU32(&x711, &x712, x7, (arg2[0])); var x713: u32 = undefined; var x714: u1 = undefined; fiatSecp256k1AddcarryxU32(&x713, &x714, 0x0, x712, x709); var x715: u32 = undefined; var x716: u1 = undefined; fiatSecp256k1AddcarryxU32(&x715, &x716, x714, x710, x707); var x717: u32 = undefined; var x718: u1 = undefined; fiatSecp256k1AddcarryxU32(&x717, &x718, x716, x708, x705); var x719: u32 = undefined; var x720: u1 = undefined; fiatSecp256k1AddcarryxU32(&x719, &x720, x718, x706, x703); var x721: u32 = undefined; var x722: u1 = undefined; fiatSecp256k1AddcarryxU32(&x721, &x722, x720, x704, x701); var x723: u32 = undefined; var x724: u1 = undefined; fiatSecp256k1AddcarryxU32(&x723, &x724, x722, x702, x699); var x725: u32 = undefined; var x726: u1 = undefined; fiatSecp256k1AddcarryxU32(&x725, &x726, x724, x700, x697); const x727: u32 = (@intCast(u32, x726) + x698); var x728: u32 = undefined; var x729: u1 = undefined; fiatSecp256k1AddcarryxU32(&x728, &x729, 0x0, x680, x711); var x730: u32 = undefined; var x731: u1 = undefined; fiatSecp256k1AddcarryxU32(&x730, &x731, x729, x682, x713); var x732: u32 = undefined; var x733: u1 = undefined; fiatSecp256k1AddcarryxU32(&x732, &x733, x731, x684, x715); var x734: u32 = undefined; var x735: u1 = undefined; fiatSecp256k1AddcarryxU32(&x734, &x735, x733, x686, x717); var x736: u32 = undefined; var x737: u1 = undefined; fiatSecp256k1AddcarryxU32(&x736, &x737, x735, x688, x719); var x738: u32 = undefined; var x739: u1 = undefined; fiatSecp256k1AddcarryxU32(&x738, &x739, x737, x690, x721); var x740: u32 = undefined; var x741: u1 = undefined; fiatSecp256k1AddcarryxU32(&x740, &x741, x739, x692, x723); var x742: u32 = undefined; var x743: u1 = undefined; fiatSecp256k1AddcarryxU32(&x742, &x743, x741, x694, x725); var x744: u32 = undefined; var x745: u1 = undefined; fiatSecp256k1AddcarryxU32(&x744, &x745, x743, x696, x727); var x746: u32 = undefined; var x747: u32 = undefined; fiatSecp256k1MulxU32(&x746, &x747, x728, 0xd2253531); var x748: u32 = undefined; var x749: u32 = undefined; fiatSecp256k1MulxU32(&x748, &x749, x746, 0xffffffff); var x750: u32 = undefined; var x751: u32 = undefined; fiatSecp256k1MulxU32(&x750, &x751, x746, 0xffffffff); var x752: u32 = undefined; var x753: u32 = undefined; fiatSecp256k1MulxU32(&x752, &x753, x746, 0xffffffff); var x754: u32 = undefined; var x755: u32 = undefined; fiatSecp256k1MulxU32(&x754, &x755, x746, 0xffffffff); var x756: u32 = undefined; var x757: u32 = undefined; fiatSecp256k1MulxU32(&x756, &x757, x746, 0xffffffff); var x758: u32 = undefined; var x759: u32 = undefined; fiatSecp256k1MulxU32(&x758, &x759, x746, 0xffffffff); var x760: u32 = undefined; var x761: u32 = undefined; fiatSecp256k1MulxU32(&x760, &x761, x746, 0xfffffffe); var x762: u32 = undefined; var x763: u32 = undefined; fiatSecp256k1MulxU32(&x762, &x763, x746, 0xfffffc2f); var x764: u32 = undefined; var x765: u1 = undefined; fiatSecp256k1AddcarryxU32(&x764, &x765, 0x0, x763, x760); var x766: u32 = undefined; var x767: u1 = undefined; fiatSecp256k1AddcarryxU32(&x766, &x767, x765, x761, x758); var x768: u32 = undefined; var x769: u1 = undefined; fiatSecp256k1AddcarryxU32(&x768, &x769, x767, x759, x756); var x770: u32 = undefined; var x771: u1 = undefined; fiatSecp256k1AddcarryxU32(&x770, &x771, x769, x757, x754); var x772: u32 = undefined; var x773: u1 = undefined; fiatSecp256k1AddcarryxU32(&x772, &x773, x771, x755, x752); var x774: u32 = undefined; var x775: u1 = undefined; fiatSecp256k1AddcarryxU32(&x774, &x775, x773, x753, x750); var x776: u32 = undefined; var x777: u1 = undefined; fiatSecp256k1AddcarryxU32(&x776, &x777, x775, x751, x748); const x778: u32 = (@intCast(u32, x777) + x749); var x779: u32 = undefined; var x780: u1 = undefined; fiatSecp256k1AddcarryxU32(&x779, &x780, 0x0, x728, x762); var x781: u32 = undefined; var x782: u1 = undefined; fiatSecp256k1AddcarryxU32(&x781, &x782, x780, x730, x764); var x783: u32 = undefined; var x784: u1 = undefined; fiatSecp256k1AddcarryxU32(&x783, &x784, x782, x732, x766); var x785: u32 = undefined; var x786: u1 = undefined; fiatSecp256k1AddcarryxU32(&x785, &x786, x784, x734, x768); var x787: u32 = undefined; var x788: u1 = undefined; fiatSecp256k1AddcarryxU32(&x787, &x788, x786, x736, x770); var x789: u32 = undefined; var x790: u1 = undefined; fiatSecp256k1AddcarryxU32(&x789, &x790, x788, x738, x772); var x791: u32 = undefined; var x792: u1 = undefined; fiatSecp256k1AddcarryxU32(&x791, &x792, x790, x740, x774); var x793: u32 = undefined; var x794: u1 = undefined; fiatSecp256k1AddcarryxU32(&x793, &x794, x792, x742, x776); var x795: u32 = undefined; var x796: u1 = undefined; fiatSecp256k1AddcarryxU32(&x795, &x796, x794, x744, x778); const x797: u32 = (@intCast(u32, x796) + @intCast(u32, x745)); var x798: u32 = undefined; var x799: u1 = undefined; fiatSecp256k1SubborrowxU32(&x798, &x799, 0x0, x781, 0xfffffc2f); var x800: u32 = undefined; var x801: u1 = undefined; fiatSecp256k1SubborrowxU32(&x800, &x801, x799, x783, 0xfffffffe); var x802: u32 = undefined; var x803: u1 = undefined; fiatSecp256k1SubborrowxU32(&x802, &x803, x801, x785, 0xffffffff); var x804: u32 = undefined; var x805: u1 = undefined; fiatSecp256k1SubborrowxU32(&x804, &x805, x803, x787, 0xffffffff); var x806: u32 = undefined; var x807: u1 = undefined; fiatSecp256k1SubborrowxU32(&x806, &x807, x805, x789, 0xffffffff); var x808: u32 = undefined; var x809: u1 = undefined; fiatSecp256k1SubborrowxU32(&x808, &x809, x807, x791, 0xffffffff); var x810: u32 = undefined; var x811: u1 = undefined; fiatSecp256k1SubborrowxU32(&x810, &x811, x809, x793, 0xffffffff); var x812: u32 = undefined; var x813: u1 = undefined; fiatSecp256k1SubborrowxU32(&x812, &x813, x811, x795, 0xffffffff); var x814: u32 = undefined; var x815: u1 = undefined; fiatSecp256k1SubborrowxU32(&x814, &x815, x813, x797, @intCast(u32, 0x0)); var x816: u32 = undefined; fiatSecp256k1CmovznzU32(&x816, x815, x798, x781); var x817: u32 = undefined; fiatSecp256k1CmovznzU32(&x817, x815, x800, x783); var x818: u32 = undefined; fiatSecp256k1CmovznzU32(&x818, x815, x802, x785); var x819: u32 = undefined; fiatSecp256k1CmovznzU32(&x819, x815, x804, x787); var x820: u32 = undefined; fiatSecp256k1CmovznzU32(&x820, x815, x806, x789); var x821: u32 = undefined; fiatSecp256k1CmovznzU32(&x821, x815, x808, x791); var x822: u32 = undefined; fiatSecp256k1CmovznzU32(&x822, x815, x810, x793); var x823: u32 = undefined; fiatSecp256k1CmovznzU32(&x823, x815, x812, x795); out1[0] = x816; out1[1] = x817; out1[2] = x818; out1[3] = x819; out1[4] = x820; out1[5] = x821; out1[6] = x822; out1[7] = x823; } /// The function fiatSecp256k1Square squares a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Square(out1: *[8]u32, arg1: [8]u32) void { const x1: u32 = (arg1[1]); const x2: u32 = (arg1[2]); const x3: u32 = (arg1[3]); const x4: u32 = (arg1[4]); const x5: u32 = (arg1[5]); const x6: u32 = (arg1[6]); const x7: u32 = (arg1[7]); const x8: u32 = (arg1[0]); var x9: u32 = undefined; var x10: u32 = undefined; fiatSecp256k1MulxU32(&x9, &x10, x8, (arg1[7])); var x11: u32 = undefined; var x12: u32 = undefined; fiatSecp256k1MulxU32(&x11, &x12, x8, (arg1[6])); var x13: u32 = undefined; var x14: u32 = undefined; fiatSecp256k1MulxU32(&x13, &x14, x8, (arg1[5])); var x15: u32 = undefined; var x16: u32 = undefined; fiatSecp256k1MulxU32(&x15, &x16, x8, (arg1[4])); var x17: u32 = undefined; var x18: u32 = undefined; fiatSecp256k1MulxU32(&x17, &x18, x8, (arg1[3])); var x19: u32 = undefined; var x20: u32 = undefined; fiatSecp256k1MulxU32(&x19, &x20, x8, (arg1[2])); var x21: u32 = undefined; var x22: u32 = undefined; fiatSecp256k1MulxU32(&x21, &x22, x8, (arg1[1])); var x23: u32 = undefined; var x24: u32 = undefined; fiatSecp256k1MulxU32(&x23, &x24, x8, (arg1[0])); var x25: u32 = undefined; var x26: u1 = undefined; fiatSecp256k1AddcarryxU32(&x25, &x26, 0x0, x24, x21); var x27: u32 = undefined; var x28: u1 = undefined; fiatSecp256k1AddcarryxU32(&x27, &x28, x26, x22, x19); var x29: u32 = undefined; var x30: u1 = undefined; fiatSecp256k1AddcarryxU32(&x29, &x30, x28, x20, x17); var x31: u32 = undefined; var x32: u1 = undefined; fiatSecp256k1AddcarryxU32(&x31, &x32, x30, x18, x15); var x33: u32 = undefined; var x34: u1 = undefined; fiatSecp256k1AddcarryxU32(&x33, &x34, x32, x16, x13); var x35: u32 = undefined; var x36: u1 = undefined; fiatSecp256k1AddcarryxU32(&x35, &x36, x34, x14, x11); var x37: u32 = undefined; var x38: u1 = undefined; fiatSecp256k1AddcarryxU32(&x37, &x38, x36, x12, x9); const x39: u32 = (@intCast(u32, x38) + x10); var x40: u32 = undefined; var x41: u32 = undefined; fiatSecp256k1MulxU32(&x40, &x41, x23, 0xd2253531); var x42: u32 = undefined; var x43: u32 = undefined; fiatSecp256k1MulxU32(&x42, &x43, x40, 0xffffffff); var x44: u32 = undefined; var x45: u32 = undefined; fiatSecp256k1MulxU32(&x44, &x45, x40, 0xffffffff); var x46: u32 = undefined; var x47: u32 = undefined; fiatSecp256k1MulxU32(&x46, &x47, x40, 0xffffffff); var x48: u32 = undefined; var x49: u32 = undefined; fiatSecp256k1MulxU32(&x48, &x49, x40, 0xffffffff); var x50: u32 = undefined; var x51: u32 = undefined; fiatSecp256k1MulxU32(&x50, &x51, x40, 0xffffffff); var x52: u32 = undefined; var x53: u32 = undefined; fiatSecp256k1MulxU32(&x52, &x53, x40, 0xffffffff); var x54: u32 = undefined; var x55: u32 = undefined; fiatSecp256k1MulxU32(&x54, &x55, x40, 0xfffffffe); var x56: u32 = undefined; var x57: u32 = undefined; fiatSecp256k1MulxU32(&x56, &x57, x40, 0xfffffc2f); var x58: u32 = undefined; var x59: u1 = undefined; fiatSecp256k1AddcarryxU32(&x58, &x59, 0x0, x57, x54); var x60: u32 = undefined; var x61: u1 = undefined; fiatSecp256k1AddcarryxU32(&x60, &x61, x59, x55, x52); var x62: u32 = undefined; var x63: u1 = undefined; fiatSecp256k1AddcarryxU32(&x62, &x63, x61, x53, x50); var x64: u32 = undefined; var x65: u1 = undefined; fiatSecp256k1AddcarryxU32(&x64, &x65, x63, x51, x48); var x66: u32 = undefined; var x67: u1 = undefined; fiatSecp256k1AddcarryxU32(&x66, &x67, x65, x49, x46); var x68: u32 = undefined; var x69: u1 = undefined; fiatSecp256k1AddcarryxU32(&x68, &x69, x67, x47, x44); var x70: u32 = undefined; var x71: u1 = undefined; fiatSecp256k1AddcarryxU32(&x70, &x71, x69, x45, x42); const x72: u32 = (@intCast(u32, x71) + x43); var x73: u32 = undefined; var x74: u1 = undefined; fiatSecp256k1AddcarryxU32(&x73, &x74, 0x0, x23, x56); var x75: u32 = undefined; var x76: u1 = undefined; fiatSecp256k1AddcarryxU32(&x75, &x76, x74, x25, x58); var x77: u32 = undefined; var x78: u1 = undefined; fiatSecp256k1AddcarryxU32(&x77, &x78, x76, x27, x60); var x79: u32 = undefined; var x80: u1 = undefined; fiatSecp256k1AddcarryxU32(&x79, &x80, x78, x29, x62); var x81: u32 = undefined; var x82: u1 = undefined; fiatSecp256k1AddcarryxU32(&x81, &x82, x80, x31, x64); var x83: u32 = undefined; var x84: u1 = undefined; fiatSecp256k1AddcarryxU32(&x83, &x84, x82, x33, x66); var x85: u32 = undefined; var x86: u1 = undefined; fiatSecp256k1AddcarryxU32(&x85, &x86, x84, x35, x68); var x87: u32 = undefined; var x88: u1 = undefined; fiatSecp256k1AddcarryxU32(&x87, &x88, x86, x37, x70); var x89: u32 = undefined; var x90: u1 = undefined; fiatSecp256k1AddcarryxU32(&x89, &x90, x88, x39, x72); var x91: u32 = undefined; var x92: u32 = undefined; fiatSecp256k1MulxU32(&x91, &x92, x1, (arg1[7])); var x93: u32 = undefined; var x94: u32 = undefined; fiatSecp256k1MulxU32(&x93, &x94, x1, (arg1[6])); var x95: u32 = undefined; var x96: u32 = undefined; fiatSecp256k1MulxU32(&x95, &x96, x1, (arg1[5])); var x97: u32 = undefined; var x98: u32 = undefined; fiatSecp256k1MulxU32(&x97, &x98, x1, (arg1[4])); var x99: u32 = undefined; var x100: u32 = undefined; fiatSecp256k1MulxU32(&x99, &x100, x1, (arg1[3])); var x101: u32 = undefined; var x102: u32 = undefined; fiatSecp256k1MulxU32(&x101, &x102, x1, (arg1[2])); var x103: u32 = undefined; var x104: u32 = undefined; fiatSecp256k1MulxU32(&x103, &x104, x1, (arg1[1])); var x105: u32 = undefined; var x106: u32 = undefined; fiatSecp256k1MulxU32(&x105, &x106, x1, (arg1[0])); var x107: u32 = undefined; var x108: u1 = undefined; fiatSecp256k1AddcarryxU32(&x107, &x108, 0x0, x106, x103); var x109: u32 = undefined; var x110: u1 = undefined; fiatSecp256k1AddcarryxU32(&x109, &x110, x108, x104, x101); var x111: u32 = undefined; var x112: u1 = undefined; fiatSecp256k1AddcarryxU32(&x111, &x112, x110, x102, x99); var x113: u32 = undefined; var x114: u1 = undefined; fiatSecp256k1AddcarryxU32(&x113, &x114, x112, x100, x97); var x115: u32 = undefined; var x116: u1 = undefined; fiatSecp256k1AddcarryxU32(&x115, &x116, x114, x98, x95); var x117: u32 = undefined; var x118: u1 = undefined; fiatSecp256k1AddcarryxU32(&x117, &x118, x116, x96, x93); var x119: u32 = undefined; var x120: u1 = undefined; fiatSecp256k1AddcarryxU32(&x119, &x120, x118, x94, x91); const x121: u32 = (@intCast(u32, x120) + x92); var x122: u32 = undefined; var x123: u1 = undefined; fiatSecp256k1AddcarryxU32(&x122, &x123, 0x0, x75, x105); var x124: u32 = undefined; var x125: u1 = undefined; fiatSecp256k1AddcarryxU32(&x124, &x125, x123, x77, x107); var x126: u32 = undefined; var x127: u1 = undefined; fiatSecp256k1AddcarryxU32(&x126, &x127, x125, x79, x109); var x128: u32 = undefined; var x129: u1 = undefined; fiatSecp256k1AddcarryxU32(&x128, &x129, x127, x81, x111); var x130: u32 = undefined; var x131: u1 = undefined; fiatSecp256k1AddcarryxU32(&x130, &x131, x129, x83, x113); var x132: u32 = undefined; var x133: u1 = undefined; fiatSecp256k1AddcarryxU32(&x132, &x133, x131, x85, x115); var x134: u32 = undefined; var x135: u1 = undefined; fiatSecp256k1AddcarryxU32(&x134, &x135, x133, x87, x117); var x136: u32 = undefined; var x137: u1 = undefined; fiatSecp256k1AddcarryxU32(&x136, &x137, x135, x89, x119); var x138: u32 = undefined; var x139: u1 = undefined; fiatSecp256k1AddcarryxU32(&x138, &x139, x137, @intCast(u32, x90), x121); var x140: u32 = undefined; var x141: u32 = undefined; fiatSecp256k1MulxU32(&x140, &x141, x122, 0xd2253531); var x142: u32 = undefined; var x143: u32 = undefined; fiatSecp256k1MulxU32(&x142, &x143, x140, 0xffffffff); var x144: u32 = undefined; var x145: u32 = undefined; fiatSecp256k1MulxU32(&x144, &x145, x140, 0xffffffff); var x146: u32 = undefined; var x147: u32 = undefined; fiatSecp256k1MulxU32(&x146, &x147, x140, 0xffffffff); var x148: u32 = undefined; var x149: u32 = undefined; fiatSecp256k1MulxU32(&x148, &x149, x140, 0xffffffff); var x150: u32 = undefined; var x151: u32 = undefined; fiatSecp256k1MulxU32(&x150, &x151, x140, 0xffffffff); var x152: u32 = undefined; var x153: u32 = undefined; fiatSecp256k1MulxU32(&x152, &x153, x140, 0xffffffff); var x154: u32 = undefined; var x155: u32 = undefined; fiatSecp256k1MulxU32(&x154, &x155, x140, 0xfffffffe); var x156: u32 = undefined; var x157: u32 = undefined; fiatSecp256k1MulxU32(&x156, &x157, x140, 0xfffffc2f); var x158: u32 = undefined; var x159: u1 = undefined; fiatSecp256k1AddcarryxU32(&x158, &x159, 0x0, x157, x154); var x160: u32 = undefined; var x161: u1 = undefined; fiatSecp256k1AddcarryxU32(&x160, &x161, x159, x155, x152); var x162: u32 = undefined; var x163: u1 = undefined; fiatSecp256k1AddcarryxU32(&x162, &x163, x161, x153, x150); var x164: u32 = undefined; var x165: u1 = undefined; fiatSecp256k1AddcarryxU32(&x164, &x165, x163, x151, x148); var x166: u32 = undefined; var x167: u1 = undefined; fiatSecp256k1AddcarryxU32(&x166, &x167, x165, x149, x146); var x168: u32 = undefined; var x169: u1 = undefined; fiatSecp256k1AddcarryxU32(&x168, &x169, x167, x147, x144); var x170: u32 = undefined; var x171: u1 = undefined; fiatSecp256k1AddcarryxU32(&x170, &x171, x169, x145, x142); const x172: u32 = (@intCast(u32, x171) + x143); var x173: u32 = undefined; var x174: u1 = undefined; fiatSecp256k1AddcarryxU32(&x173, &x174, 0x0, x122, x156); var x175: u32 = undefined; var x176: u1 = undefined; fiatSecp256k1AddcarryxU32(&x175, &x176, x174, x124, x158); var x177: u32 = undefined; var x178: u1 = undefined; fiatSecp256k1AddcarryxU32(&x177, &x178, x176, x126, x160); var x179: u32 = undefined; var x180: u1 = undefined; fiatSecp256k1AddcarryxU32(&x179, &x180, x178, x128, x162); var x181: u32 = undefined; var x182: u1 = undefined; fiatSecp256k1AddcarryxU32(&x181, &x182, x180, x130, x164); var x183: u32 = undefined; var x184: u1 = undefined; fiatSecp256k1AddcarryxU32(&x183, &x184, x182, x132, x166); var x185: u32 = undefined; var x186: u1 = undefined; fiatSecp256k1AddcarryxU32(&x185, &x186, x184, x134, x168); var x187: u32 = undefined; var x188: u1 = undefined; fiatSecp256k1AddcarryxU32(&x187, &x188, x186, x136, x170); var x189: u32 = undefined; var x190: u1 = undefined; fiatSecp256k1AddcarryxU32(&x189, &x190, x188, x138, x172); const x191: u32 = (@intCast(u32, x190) + @intCast(u32, x139)); var x192: u32 = undefined; var x193: u32 = undefined; fiatSecp256k1MulxU32(&x192, &x193, x2, (arg1[7])); var x194: u32 = undefined; var x195: u32 = undefined; fiatSecp256k1MulxU32(&x194, &x195, x2, (arg1[6])); var x196: u32 = undefined; var x197: u32 = undefined; fiatSecp256k1MulxU32(&x196, &x197, x2, (arg1[5])); var x198: u32 = undefined; var x199: u32 = undefined; fiatSecp256k1MulxU32(&x198, &x199, x2, (arg1[4])); var x200: u32 = undefined; var x201: u32 = undefined; fiatSecp256k1MulxU32(&x200, &x201, x2, (arg1[3])); var x202: u32 = undefined; var x203: u32 = undefined; fiatSecp256k1MulxU32(&x202, &x203, x2, (arg1[2])); var x204: u32 = undefined; var x205: u32 = undefined; fiatSecp256k1MulxU32(&x204, &x205, x2, (arg1[1])); var x206: u32 = undefined; var x207: u32 = undefined; fiatSecp256k1MulxU32(&x206, &x207, x2, (arg1[0])); var x208: u32 = undefined; var x209: u1 = undefined; fiatSecp256k1AddcarryxU32(&x208, &x209, 0x0, x207, x204); var x210: u32 = undefined; var x211: u1 = undefined; fiatSecp256k1AddcarryxU32(&x210, &x211, x209, x205, x202); var x212: u32 = undefined; var x213: u1 = undefined; fiatSecp256k1AddcarryxU32(&x212, &x213, x211, x203, x200); var x214: u32 = undefined; var x215: u1 = undefined; fiatSecp256k1AddcarryxU32(&x214, &x215, x213, x201, x198); var x216: u32 = undefined; var x217: u1 = undefined; fiatSecp256k1AddcarryxU32(&x216, &x217, x215, x199, x196); var x218: u32 = undefined; var x219: u1 = undefined; fiatSecp256k1AddcarryxU32(&x218, &x219, x217, x197, x194); var x220: u32 = undefined; var x221: u1 = undefined; fiatSecp256k1AddcarryxU32(&x220, &x221, x219, x195, x192); const x222: u32 = (@intCast(u32, x221) + x193); var x223: u32 = undefined; var x224: u1 = undefined; fiatSecp256k1AddcarryxU32(&x223, &x224, 0x0, x175, x206); var x225: u32 = undefined; var x226: u1 = undefined; fiatSecp256k1AddcarryxU32(&x225, &x226, x224, x177, x208); var x227: u32 = undefined; var x228: u1 = undefined; fiatSecp256k1AddcarryxU32(&x227, &x228, x226, x179, x210); var x229: u32 = undefined; var x230: u1 = undefined; fiatSecp256k1AddcarryxU32(&x229, &x230, x228, x181, x212); var x231: u32 = undefined; var x232: u1 = undefined; fiatSecp256k1AddcarryxU32(&x231, &x232, x230, x183, x214); var x233: u32 = undefined; var x234: u1 = undefined; fiatSecp256k1AddcarryxU32(&x233, &x234, x232, x185, x216); var x235: u32 = undefined; var x236: u1 = undefined; fiatSecp256k1AddcarryxU32(&x235, &x236, x234, x187, x218); var x237: u32 = undefined; var x238: u1 = undefined; fiatSecp256k1AddcarryxU32(&x237, &x238, x236, x189, x220); var x239: u32 = undefined; var x240: u1 = undefined; fiatSecp256k1AddcarryxU32(&x239, &x240, x238, x191, x222); var x241: u32 = undefined; var x242: u32 = undefined; fiatSecp256k1MulxU32(&x241, &x242, x223, 0xd2253531); var x243: u32 = undefined; var x244: u32 = undefined; fiatSecp256k1MulxU32(&x243, &x244, x241, 0xffffffff); var x245: u32 = undefined; var x246: u32 = undefined; fiatSecp256k1MulxU32(&x245, &x246, x241, 0xffffffff); var x247: u32 = undefined; var x248: u32 = undefined; fiatSecp256k1MulxU32(&x247, &x248, x241, 0xffffffff); var x249: u32 = undefined; var x250: u32 = undefined; fiatSecp256k1MulxU32(&x249, &x250, x241, 0xffffffff); var x251: u32 = undefined; var x252: u32 = undefined; fiatSecp256k1MulxU32(&x251, &x252, x241, 0xffffffff); var x253: u32 = undefined; var x254: u32 = undefined; fiatSecp256k1MulxU32(&x253, &x254, x241, 0xffffffff); var x255: u32 = undefined; var x256: u32 = undefined; fiatSecp256k1MulxU32(&x255, &x256, x241, 0xfffffffe); var x257: u32 = undefined; var x258: u32 = undefined; fiatSecp256k1MulxU32(&x257, &x258, x241, 0xfffffc2f); var x259: u32 = undefined; var x260: u1 = undefined; fiatSecp256k1AddcarryxU32(&x259, &x260, 0x0, x258, x255); var x261: u32 = undefined; var x262: u1 = undefined; fiatSecp256k1AddcarryxU32(&x261, &x262, x260, x256, x253); var x263: u32 = undefined; var x264: u1 = undefined; fiatSecp256k1AddcarryxU32(&x263, &x264, x262, x254, x251); var x265: u32 = undefined; var x266: u1 = undefined; fiatSecp256k1AddcarryxU32(&x265, &x266, x264, x252, x249); var x267: u32 = undefined; var x268: u1 = undefined; fiatSecp256k1AddcarryxU32(&x267, &x268, x266, x250, x247); var x269: u32 = undefined; var x270: u1 = undefined; fiatSecp256k1AddcarryxU32(&x269, &x270, x268, x248, x245); var x271: u32 = undefined; var x272: u1 = undefined; fiatSecp256k1AddcarryxU32(&x271, &x272, x270, x246, x243); const x273: u32 = (@intCast(u32, x272) + x244); var x274: u32 = undefined; var x275: u1 = undefined; fiatSecp256k1AddcarryxU32(&x274, &x275, 0x0, x223, x257); var x276: u32 = undefined; var x277: u1 = undefined; fiatSecp256k1AddcarryxU32(&x276, &x277, x275, x225, x259); var x278: u32 = undefined; var x279: u1 = undefined; fiatSecp256k1AddcarryxU32(&x278, &x279, x277, x227, x261); var x280: u32 = undefined; var x281: u1 = undefined; fiatSecp256k1AddcarryxU32(&x280, &x281, x279, x229, x263); var x282: u32 = undefined; var x283: u1 = undefined; fiatSecp256k1AddcarryxU32(&x282, &x283, x281, x231, x265); var x284: u32 = undefined; var x285: u1 = undefined; fiatSecp256k1AddcarryxU32(&x284, &x285, x283, x233, x267); var x286: u32 = undefined; var x287: u1 = undefined; fiatSecp256k1AddcarryxU32(&x286, &x287, x285, x235, x269); var x288: u32 = undefined; var x289: u1 = undefined; fiatSecp256k1AddcarryxU32(&x288, &x289, x287, x237, x271); var x290: u32 = undefined; var x291: u1 = undefined; fiatSecp256k1AddcarryxU32(&x290, &x291, x289, x239, x273); const x292: u32 = (@intCast(u32, x291) + @intCast(u32, x240)); var x293: u32 = undefined; var x294: u32 = undefined; fiatSecp256k1MulxU32(&x293, &x294, x3, (arg1[7])); var x295: u32 = undefined; var x296: u32 = undefined; fiatSecp256k1MulxU32(&x295, &x296, x3, (arg1[6])); var x297: u32 = undefined; var x298: u32 = undefined; fiatSecp256k1MulxU32(&x297, &x298, x3, (arg1[5])); var x299: u32 = undefined; var x300: u32 = undefined; fiatSecp256k1MulxU32(&x299, &x300, x3, (arg1[4])); var x301: u32 = undefined; var x302: u32 = undefined; fiatSecp256k1MulxU32(&x301, &x302, x3, (arg1[3])); var x303: u32 = undefined; var x304: u32 = undefined; fiatSecp256k1MulxU32(&x303, &x304, x3, (arg1[2])); var x305: u32 = undefined; var x306: u32 = undefined; fiatSecp256k1MulxU32(&x305, &x306, x3, (arg1[1])); var x307: u32 = undefined; var x308: u32 = undefined; fiatSecp256k1MulxU32(&x307, &x308, x3, (arg1[0])); var x309: u32 = undefined; var x310: u1 = undefined; fiatSecp256k1AddcarryxU32(&x309, &x310, 0x0, x308, x305); var x311: u32 = undefined; var x312: u1 = undefined; fiatSecp256k1AddcarryxU32(&x311, &x312, x310, x306, x303); var x313: u32 = undefined; var x314: u1 = undefined; fiatSecp256k1AddcarryxU32(&x313, &x314, x312, x304, x301); var x315: u32 = undefined; var x316: u1 = undefined; fiatSecp256k1AddcarryxU32(&x315, &x316, x314, x302, x299); var x317: u32 = undefined; var x318: u1 = undefined; fiatSecp256k1AddcarryxU32(&x317, &x318, x316, x300, x297); var x319: u32 = undefined; var x320: u1 = undefined; fiatSecp256k1AddcarryxU32(&x319, &x320, x318, x298, x295); var x321: u32 = undefined; var x322: u1 = undefined; fiatSecp256k1AddcarryxU32(&x321, &x322, x320, x296, x293); const x323: u32 = (@intCast(u32, x322) + x294); var x324: u32 = undefined; var x325: u1 = undefined; fiatSecp256k1AddcarryxU32(&x324, &x325, 0x0, x276, x307); var x326: u32 = undefined; var x327: u1 = undefined; fiatSecp256k1AddcarryxU32(&x326, &x327, x325, x278, x309); var x328: u32 = undefined; var x329: u1 = undefined; fiatSecp256k1AddcarryxU32(&x328, &x329, x327, x280, x311); var x330: u32 = undefined; var x331: u1 = undefined; fiatSecp256k1AddcarryxU32(&x330, &x331, x329, x282, x313); var x332: u32 = undefined; var x333: u1 = undefined; fiatSecp256k1AddcarryxU32(&x332, &x333, x331, x284, x315); var x334: u32 = undefined; var x335: u1 = undefined; fiatSecp256k1AddcarryxU32(&x334, &x335, x333, x286, x317); var x336: u32 = undefined; var x337: u1 = undefined; fiatSecp256k1AddcarryxU32(&x336, &x337, x335, x288, x319); var x338: u32 = undefined; var x339: u1 = undefined; fiatSecp256k1AddcarryxU32(&x338, &x339, x337, x290, x321); var x340: u32 = undefined; var x341: u1 = undefined; fiatSecp256k1AddcarryxU32(&x340, &x341, x339, x292, x323); var x342: u32 = undefined; var x343: u32 = undefined; fiatSecp256k1MulxU32(&x342, &x343, x324, 0xd2253531); var x344: u32 = undefined; var x345: u32 = undefined; fiatSecp256k1MulxU32(&x344, &x345, x342, 0xffffffff); var x346: u32 = undefined; var x347: u32 = undefined; fiatSecp256k1MulxU32(&x346, &x347, x342, 0xffffffff); var x348: u32 = undefined; var x349: u32 = undefined; fiatSecp256k1MulxU32(&x348, &x349, x342, 0xffffffff); var x350: u32 = undefined; var x351: u32 = undefined; fiatSecp256k1MulxU32(&x350, &x351, x342, 0xffffffff); var x352: u32 = undefined; var x353: u32 = undefined; fiatSecp256k1MulxU32(&x352, &x353, x342, 0xffffffff); var x354: u32 = undefined; var x355: u32 = undefined; fiatSecp256k1MulxU32(&x354, &x355, x342, 0xffffffff); var x356: u32 = undefined; var x357: u32 = undefined; fiatSecp256k1MulxU32(&x356, &x357, x342, 0xfffffffe); var x358: u32 = undefined; var x359: u32 = undefined; fiatSecp256k1MulxU32(&x358, &x359, x342, 0xfffffc2f); var x360: u32 = undefined; var x361: u1 = undefined; fiatSecp256k1AddcarryxU32(&x360, &x361, 0x0, x359, x356); var x362: u32 = undefined; var x363: u1 = undefined; fiatSecp256k1AddcarryxU32(&x362, &x363, x361, x357, x354); var x364: u32 = undefined; var x365: u1 = undefined; fiatSecp256k1AddcarryxU32(&x364, &x365, x363, x355, x352); var x366: u32 = undefined; var x367: u1 = undefined; fiatSecp256k1AddcarryxU32(&x366, &x367, x365, x353, x350); var x368: u32 = undefined; var x369: u1 = undefined; fiatSecp256k1AddcarryxU32(&x368, &x369, x367, x351, x348); var x370: u32 = undefined; var x371: u1 = undefined; fiatSecp256k1AddcarryxU32(&x370, &x371, x369, x349, x346); var x372: u32 = undefined; var x373: u1 = undefined; fiatSecp256k1AddcarryxU32(&x372, &x373, x371, x347, x344); const x374: u32 = (@intCast(u32, x373) + x345); var x375: u32 = undefined; var x376: u1 = undefined; fiatSecp256k1AddcarryxU32(&x375, &x376, 0x0, x324, x358); var x377: u32 = undefined; var x378: u1 = undefined; fiatSecp256k1AddcarryxU32(&x377, &x378, x376, x326, x360); var x379: u32 = undefined; var x380: u1 = undefined; fiatSecp256k1AddcarryxU32(&x379, &x380, x378, x328, x362); var x381: u32 = undefined; var x382: u1 = undefined; fiatSecp256k1AddcarryxU32(&x381, &x382, x380, x330, x364); var x383: u32 = undefined; var x384: u1 = undefined; fiatSecp256k1AddcarryxU32(&x383, &x384, x382, x332, x366); var x385: u32 = undefined; var x386: u1 = undefined; fiatSecp256k1AddcarryxU32(&x385, &x386, x384, x334, x368); var x387: u32 = undefined; var x388: u1 = undefined; fiatSecp256k1AddcarryxU32(&x387, &x388, x386, x336, x370); var x389: u32 = undefined; var x390: u1 = undefined; fiatSecp256k1AddcarryxU32(&x389, &x390, x388, x338, x372); var x391: u32 = undefined; var x392: u1 = undefined; fiatSecp256k1AddcarryxU32(&x391, &x392, x390, x340, x374); const x393: u32 = (@intCast(u32, x392) + @intCast(u32, x341)); var x394: u32 = undefined; var x395: u32 = undefined; fiatSecp256k1MulxU32(&x394, &x395, x4, (arg1[7])); var x396: u32 = undefined; var x397: u32 = undefined; fiatSecp256k1MulxU32(&x396, &x397, x4, (arg1[6])); var x398: u32 = undefined; var x399: u32 = undefined; fiatSecp256k1MulxU32(&x398, &x399, x4, (arg1[5])); var x400: u32 = undefined; var x401: u32 = undefined; fiatSecp256k1MulxU32(&x400, &x401, x4, (arg1[4])); var x402: u32 = undefined; var x403: u32 = undefined; fiatSecp256k1MulxU32(&x402, &x403, x4, (arg1[3])); var x404: u32 = undefined; var x405: u32 = undefined; fiatSecp256k1MulxU32(&x404, &x405, x4, (arg1[2])); var x406: u32 = undefined; var x407: u32 = undefined; fiatSecp256k1MulxU32(&x406, &x407, x4, (arg1[1])); var x408: u32 = undefined; var x409: u32 = undefined; fiatSecp256k1MulxU32(&x408, &x409, x4, (arg1[0])); var x410: u32 = undefined; var x411: u1 = undefined; fiatSecp256k1AddcarryxU32(&x410, &x411, 0x0, x409, x406); var x412: u32 = undefined; var x413: u1 = undefined; fiatSecp256k1AddcarryxU32(&x412, &x413, x411, x407, x404); var x414: u32 = undefined; var x415: u1 = undefined; fiatSecp256k1AddcarryxU32(&x414, &x415, x413, x405, x402); var x416: u32 = undefined; var x417: u1 = undefined; fiatSecp256k1AddcarryxU32(&x416, &x417, x415, x403, x400); var x418: u32 = undefined; var x419: u1 = undefined; fiatSecp256k1AddcarryxU32(&x418, &x419, x417, x401, x398); var x420: u32 = undefined; var x421: u1 = undefined; fiatSecp256k1AddcarryxU32(&x420, &x421, x419, x399, x396); var x422: u32 = undefined; var x423: u1 = undefined; fiatSecp256k1AddcarryxU32(&x422, &x423, x421, x397, x394); const x424: u32 = (@intCast(u32, x423) + x395); var x425: u32 = undefined; var x426: u1 = undefined; fiatSecp256k1AddcarryxU32(&x425, &x426, 0x0, x377, x408); var x427: u32 = undefined; var x428: u1 = undefined; fiatSecp256k1AddcarryxU32(&x427, &x428, x426, x379, x410); var x429: u32 = undefined; var x430: u1 = undefined; fiatSecp256k1AddcarryxU32(&x429, &x430, x428, x381, x412); var x431: u32 = undefined; var x432: u1 = undefined; fiatSecp256k1AddcarryxU32(&x431, &x432, x430, x383, x414); var x433: u32 = undefined; var x434: u1 = undefined; fiatSecp256k1AddcarryxU32(&x433, &x434, x432, x385, x416); var x435: u32 = undefined; var x436: u1 = undefined; fiatSecp256k1AddcarryxU32(&x435, &x436, x434, x387, x418); var x437: u32 = undefined; var x438: u1 = undefined; fiatSecp256k1AddcarryxU32(&x437, &x438, x436, x389, x420); var x439: u32 = undefined; var x440: u1 = undefined; fiatSecp256k1AddcarryxU32(&x439, &x440, x438, x391, x422); var x441: u32 = undefined; var x442: u1 = undefined; fiatSecp256k1AddcarryxU32(&x441, &x442, x440, x393, x424); var x443: u32 = undefined; var x444: u32 = undefined; fiatSecp256k1MulxU32(&x443, &x444, x425, 0xd2253531); var x445: u32 = undefined; var x446: u32 = undefined; fiatSecp256k1MulxU32(&x445, &x446, x443, 0xffffffff); var x447: u32 = undefined; var x448: u32 = undefined; fiatSecp256k1MulxU32(&x447, &x448, x443, 0xffffffff); var x449: u32 = undefined; var x450: u32 = undefined; fiatSecp256k1MulxU32(&x449, &x450, x443, 0xffffffff); var x451: u32 = undefined; var x452: u32 = undefined; fiatSecp256k1MulxU32(&x451, &x452, x443, 0xffffffff); var x453: u32 = undefined; var x454: u32 = undefined; fiatSecp256k1MulxU32(&x453, &x454, x443, 0xffffffff); var x455: u32 = undefined; var x456: u32 = undefined; fiatSecp256k1MulxU32(&x455, &x456, x443, 0xffffffff); var x457: u32 = undefined; var x458: u32 = undefined; fiatSecp256k1MulxU32(&x457, &x458, x443, 0xfffffffe); var x459: u32 = undefined; var x460: u32 = undefined; fiatSecp256k1MulxU32(&x459, &x460, x443, 0xfffffc2f); var x461: u32 = undefined; var x462: u1 = undefined; fiatSecp256k1AddcarryxU32(&x461, &x462, 0x0, x460, x457); var x463: u32 = undefined; var x464: u1 = undefined; fiatSecp256k1AddcarryxU32(&x463, &x464, x462, x458, x455); var x465: u32 = undefined; var x466: u1 = undefined; fiatSecp256k1AddcarryxU32(&x465, &x466, x464, x456, x453); var x467: u32 = undefined; var x468: u1 = undefined; fiatSecp256k1AddcarryxU32(&x467, &x468, x466, x454, x451); var x469: u32 = undefined; var x470: u1 = undefined; fiatSecp256k1AddcarryxU32(&x469, &x470, x468, x452, x449); var x471: u32 = undefined; var x472: u1 = undefined; fiatSecp256k1AddcarryxU32(&x471, &x472, x470, x450, x447); var x473: u32 = undefined; var x474: u1 = undefined; fiatSecp256k1AddcarryxU32(&x473, &x474, x472, x448, x445); const x475: u32 = (@intCast(u32, x474) + x446); var x476: u32 = undefined; var x477: u1 = undefined; fiatSecp256k1AddcarryxU32(&x476, &x477, 0x0, x425, x459); var x478: u32 = undefined; var x479: u1 = undefined; fiatSecp256k1AddcarryxU32(&x478, &x479, x477, x427, x461); var x480: u32 = undefined; var x481: u1 = undefined; fiatSecp256k1AddcarryxU32(&x480, &x481, x479, x429, x463); var x482: u32 = undefined; var x483: u1 = undefined; fiatSecp256k1AddcarryxU32(&x482, &x483, x481, x431, x465); var x484: u32 = undefined; var x485: u1 = undefined; fiatSecp256k1AddcarryxU32(&x484, &x485, x483, x433, x467); var x486: u32 = undefined; var x487: u1 = undefined; fiatSecp256k1AddcarryxU32(&x486, &x487, x485, x435, x469); var x488: u32 = undefined; var x489: u1 = undefined; fiatSecp256k1AddcarryxU32(&x488, &x489, x487, x437, x471); var x490: u32 = undefined; var x491: u1 = undefined; fiatSecp256k1AddcarryxU32(&x490, &x491, x489, x439, x473); var x492: u32 = undefined; var x493: u1 = undefined; fiatSecp256k1AddcarryxU32(&x492, &x493, x491, x441, x475); const x494: u32 = (@intCast(u32, x493) + @intCast(u32, x442)); var x495: u32 = undefined; var x496: u32 = undefined; fiatSecp256k1MulxU32(&x495, &x496, x5, (arg1[7])); var x497: u32 = undefined; var x498: u32 = undefined; fiatSecp256k1MulxU32(&x497, &x498, x5, (arg1[6])); var x499: u32 = undefined; var x500: u32 = undefined; fiatSecp256k1MulxU32(&x499, &x500, x5, (arg1[5])); var x501: u32 = undefined; var x502: u32 = undefined; fiatSecp256k1MulxU32(&x501, &x502, x5, (arg1[4])); var x503: u32 = undefined; var x504: u32 = undefined; fiatSecp256k1MulxU32(&x503, &x504, x5, (arg1[3])); var x505: u32 = undefined; var x506: u32 = undefined; fiatSecp256k1MulxU32(&x505, &x506, x5, (arg1[2])); var x507: u32 = undefined; var x508: u32 = undefined; fiatSecp256k1MulxU32(&x507, &x508, x5, (arg1[1])); var x509: u32 = undefined; var x510: u32 = undefined; fiatSecp256k1MulxU32(&x509, &x510, x5, (arg1[0])); var x511: u32 = undefined; var x512: u1 = undefined; fiatSecp256k1AddcarryxU32(&x511, &x512, 0x0, x510, x507); var x513: u32 = undefined; var x514: u1 = undefined; fiatSecp256k1AddcarryxU32(&x513, &x514, x512, x508, x505); var x515: u32 = undefined; var x516: u1 = undefined; fiatSecp256k1AddcarryxU32(&x515, &x516, x514, x506, x503); var x517: u32 = undefined; var x518: u1 = undefined; fiatSecp256k1AddcarryxU32(&x517, &x518, x516, x504, x501); var x519: u32 = undefined; var x520: u1 = undefined; fiatSecp256k1AddcarryxU32(&x519, &x520, x518, x502, x499); var x521: u32 = undefined; var x522: u1 = undefined; fiatSecp256k1AddcarryxU32(&x521, &x522, x520, x500, x497); var x523: u32 = undefined; var x524: u1 = undefined; fiatSecp256k1AddcarryxU32(&x523, &x524, x522, x498, x495); const x525: u32 = (@intCast(u32, x524) + x496); var x526: u32 = undefined; var x527: u1 = undefined; fiatSecp256k1AddcarryxU32(&x526, &x527, 0x0, x478, x509); var x528: u32 = undefined; var x529: u1 = undefined; fiatSecp256k1AddcarryxU32(&x528, &x529, x527, x480, x511); var x530: u32 = undefined; var x531: u1 = undefined; fiatSecp256k1AddcarryxU32(&x530, &x531, x529, x482, x513); var x532: u32 = undefined; var x533: u1 = undefined; fiatSecp256k1AddcarryxU32(&x532, &x533, x531, x484, x515); var x534: u32 = undefined; var x535: u1 = undefined; fiatSecp256k1AddcarryxU32(&x534, &x535, x533, x486, x517); var x536: u32 = undefined; var x537: u1 = undefined; fiatSecp256k1AddcarryxU32(&x536, &x537, x535, x488, x519); var x538: u32 = undefined; var x539: u1 = undefined; fiatSecp256k1AddcarryxU32(&x538, &x539, x537, x490, x521); var x540: u32 = undefined; var x541: u1 = undefined; fiatSecp256k1AddcarryxU32(&x540, &x541, x539, x492, x523); var x542: u32 = undefined; var x543: u1 = undefined; fiatSecp256k1AddcarryxU32(&x542, &x543, x541, x494, x525); var x544: u32 = undefined; var x545: u32 = undefined; fiatSecp256k1MulxU32(&x544, &x545, x526, 0xd2253531); var x546: u32 = undefined; var x547: u32 = undefined; fiatSecp256k1MulxU32(&x546, &x547, x544, 0xffffffff); var x548: u32 = undefined; var x549: u32 = undefined; fiatSecp256k1MulxU32(&x548, &x549, x544, 0xffffffff); var x550: u32 = undefined; var x551: u32 = undefined; fiatSecp256k1MulxU32(&x550, &x551, x544, 0xffffffff); var x552: u32 = undefined; var x553: u32 = undefined; fiatSecp256k1MulxU32(&x552, &x553, x544, 0xffffffff); var x554: u32 = undefined; var x555: u32 = undefined; fiatSecp256k1MulxU32(&x554, &x555, x544, 0xffffffff); var x556: u32 = undefined; var x557: u32 = undefined; fiatSecp256k1MulxU32(&x556, &x557, x544, 0xffffffff); var x558: u32 = undefined; var x559: u32 = undefined; fiatSecp256k1MulxU32(&x558, &x559, x544, 0xfffffffe); var x560: u32 = undefined; var x561: u32 = undefined; fiatSecp256k1MulxU32(&x560, &x561, x544, 0xfffffc2f); var x562: u32 = undefined; var x563: u1 = undefined; fiatSecp256k1AddcarryxU32(&x562, &x563, 0x0, x561, x558); var x564: u32 = undefined; var x565: u1 = undefined; fiatSecp256k1AddcarryxU32(&x564, &x565, x563, x559, x556); var x566: u32 = undefined; var x567: u1 = undefined; fiatSecp256k1AddcarryxU32(&x566, &x567, x565, x557, x554); var x568: u32 = undefined; var x569: u1 = undefined; fiatSecp256k1AddcarryxU32(&x568, &x569, x567, x555, x552); var x570: u32 = undefined; var x571: u1 = undefined; fiatSecp256k1AddcarryxU32(&x570, &x571, x569, x553, x550); var x572: u32 = undefined; var x573: u1 = undefined; fiatSecp256k1AddcarryxU32(&x572, &x573, x571, x551, x548); var x574: u32 = undefined; var x575: u1 = undefined; fiatSecp256k1AddcarryxU32(&x574, &x575, x573, x549, x546); const x576: u32 = (@intCast(u32, x575) + x547); var x577: u32 = undefined; var x578: u1 = undefined; fiatSecp256k1AddcarryxU32(&x577, &x578, 0x0, x526, x560); var x579: u32 = undefined; var x580: u1 = undefined; fiatSecp256k1AddcarryxU32(&x579, &x580, x578, x528, x562); var x581: u32 = undefined; var x582: u1 = undefined; fiatSecp256k1AddcarryxU32(&x581, &x582, x580, x530, x564); var x583: u32 = undefined; var x584: u1 = undefined; fiatSecp256k1AddcarryxU32(&x583, &x584, x582, x532, x566); var x585: u32 = undefined; var x586: u1 = undefined; fiatSecp256k1AddcarryxU32(&x585, &x586, x584, x534, x568); var x587: u32 = undefined; var x588: u1 = undefined; fiatSecp256k1AddcarryxU32(&x587, &x588, x586, x536, x570); var x589: u32 = undefined; var x590: u1 = undefined; fiatSecp256k1AddcarryxU32(&x589, &x590, x588, x538, x572); var x591: u32 = undefined; var x592: u1 = undefined; fiatSecp256k1AddcarryxU32(&x591, &x592, x590, x540, x574); var x593: u32 = undefined; var x594: u1 = undefined; fiatSecp256k1AddcarryxU32(&x593, &x594, x592, x542, x576); const x595: u32 = (@intCast(u32, x594) + @intCast(u32, x543)); var x596: u32 = undefined; var x597: u32 = undefined; fiatSecp256k1MulxU32(&x596, &x597, x6, (arg1[7])); var x598: u32 = undefined; var x599: u32 = undefined; fiatSecp256k1MulxU32(&x598, &x599, x6, (arg1[6])); var x600: u32 = undefined; var x601: u32 = undefined; fiatSecp256k1MulxU32(&x600, &x601, x6, (arg1[5])); var x602: u32 = undefined; var x603: u32 = undefined; fiatSecp256k1MulxU32(&x602, &x603, x6, (arg1[4])); var x604: u32 = undefined; var x605: u32 = undefined; fiatSecp256k1MulxU32(&x604, &x605, x6, (arg1[3])); var x606: u32 = undefined; var x607: u32 = undefined; fiatSecp256k1MulxU32(&x606, &x607, x6, (arg1[2])); var x608: u32 = undefined; var x609: u32 = undefined; fiatSecp256k1MulxU32(&x608, &x609, x6, (arg1[1])); var x610: u32 = undefined; var x611: u32 = undefined; fiatSecp256k1MulxU32(&x610, &x611, x6, (arg1[0])); var x612: u32 = undefined; var x613: u1 = undefined; fiatSecp256k1AddcarryxU32(&x612, &x613, 0x0, x611, x608); var x614: u32 = undefined; var x615: u1 = undefined; fiatSecp256k1AddcarryxU32(&x614, &x615, x613, x609, x606); var x616: u32 = undefined; var x617: u1 = undefined; fiatSecp256k1AddcarryxU32(&x616, &x617, x615, x607, x604); var x618: u32 = undefined; var x619: u1 = undefined; fiatSecp256k1AddcarryxU32(&x618, &x619, x617, x605, x602); var x620: u32 = undefined; var x621: u1 = undefined; fiatSecp256k1AddcarryxU32(&x620, &x621, x619, x603, x600); var x622: u32 = undefined; var x623: u1 = undefined; fiatSecp256k1AddcarryxU32(&x622, &x623, x621, x601, x598); var x624: u32 = undefined; var x625: u1 = undefined; fiatSecp256k1AddcarryxU32(&x624, &x625, x623, x599, x596); const x626: u32 = (@intCast(u32, x625) + x597); var x627: u32 = undefined; var x628: u1 = undefined; fiatSecp256k1AddcarryxU32(&x627, &x628, 0x0, x579, x610); var x629: u32 = undefined; var x630: u1 = undefined; fiatSecp256k1AddcarryxU32(&x629, &x630, x628, x581, x612); var x631: u32 = undefined; var x632: u1 = undefined; fiatSecp256k1AddcarryxU32(&x631, &x632, x630, x583, x614); var x633: u32 = undefined; var x634: u1 = undefined; fiatSecp256k1AddcarryxU32(&x633, &x634, x632, x585, x616); var x635: u32 = undefined; var x636: u1 = undefined; fiatSecp256k1AddcarryxU32(&x635, &x636, x634, x587, x618); var x637: u32 = undefined; var x638: u1 = undefined; fiatSecp256k1AddcarryxU32(&x637, &x638, x636, x589, x620); var x639: u32 = undefined; var x640: u1 = undefined; fiatSecp256k1AddcarryxU32(&x639, &x640, x638, x591, x622); var x641: u32 = undefined; var x642: u1 = undefined; fiatSecp256k1AddcarryxU32(&x641, &x642, x640, x593, x624); var x643: u32 = undefined; var x644: u1 = undefined; fiatSecp256k1AddcarryxU32(&x643, &x644, x642, x595, x626); var x645: u32 = undefined; var x646: u32 = undefined; fiatSecp256k1MulxU32(&x645, &x646, x627, 0xd2253531); var x647: u32 = undefined; var x648: u32 = undefined; fiatSecp256k1MulxU32(&x647, &x648, x645, 0xffffffff); var x649: u32 = undefined; var x650: u32 = undefined; fiatSecp256k1MulxU32(&x649, &x650, x645, 0xffffffff); var x651: u32 = undefined; var x652: u32 = undefined; fiatSecp256k1MulxU32(&x651, &x652, x645, 0xffffffff); var x653: u32 = undefined; var x654: u32 = undefined; fiatSecp256k1MulxU32(&x653, &x654, x645, 0xffffffff); var x655: u32 = undefined; var x656: u32 = undefined; fiatSecp256k1MulxU32(&x655, &x656, x645, 0xffffffff); var x657: u32 = undefined; var x658: u32 = undefined; fiatSecp256k1MulxU32(&x657, &x658, x645, 0xffffffff); var x659: u32 = undefined; var x660: u32 = undefined; fiatSecp256k1MulxU32(&x659, &x660, x645, 0xfffffffe); var x661: u32 = undefined; var x662: u32 = undefined; fiatSecp256k1MulxU32(&x661, &x662, x645, 0xfffffc2f); var x663: u32 = undefined; var x664: u1 = undefined; fiatSecp256k1AddcarryxU32(&x663, &x664, 0x0, x662, x659); var x665: u32 = undefined; var x666: u1 = undefined; fiatSecp256k1AddcarryxU32(&x665, &x666, x664, x660, x657); var x667: u32 = undefined; var x668: u1 = undefined; fiatSecp256k1AddcarryxU32(&x667, &x668, x666, x658, x655); var x669: u32 = undefined; var x670: u1 = undefined; fiatSecp256k1AddcarryxU32(&x669, &x670, x668, x656, x653); var x671: u32 = undefined; var x672: u1 = undefined; fiatSecp256k1AddcarryxU32(&x671, &x672, x670, x654, x651); var x673: u32 = undefined; var x674: u1 = undefined; fiatSecp256k1AddcarryxU32(&x673, &x674, x672, x652, x649); var x675: u32 = undefined; var x676: u1 = undefined; fiatSecp256k1AddcarryxU32(&x675, &x676, x674, x650, x647); const x677: u32 = (@intCast(u32, x676) + x648); var x678: u32 = undefined; var x679: u1 = undefined; fiatSecp256k1AddcarryxU32(&x678, &x679, 0x0, x627, x661); var x680: u32 = undefined; var x681: u1 = undefined; fiatSecp256k1AddcarryxU32(&x680, &x681, x679, x629, x663); var x682: u32 = undefined; var x683: u1 = undefined; fiatSecp256k1AddcarryxU32(&x682, &x683, x681, x631, x665); var x684: u32 = undefined; var x685: u1 = undefined; fiatSecp256k1AddcarryxU32(&x684, &x685, x683, x633, x667); var x686: u32 = undefined; var x687: u1 = undefined; fiatSecp256k1AddcarryxU32(&x686, &x687, x685, x635, x669); var x688: u32 = undefined; var x689: u1 = undefined; fiatSecp256k1AddcarryxU32(&x688, &x689, x687, x637, x671); var x690: u32 = undefined; var x691: u1 = undefined; fiatSecp256k1AddcarryxU32(&x690, &x691, x689, x639, x673); var x692: u32 = undefined; var x693: u1 = undefined; fiatSecp256k1AddcarryxU32(&x692, &x693, x691, x641, x675); var x694: u32 = undefined; var x695: u1 = undefined; fiatSecp256k1AddcarryxU32(&x694, &x695, x693, x643, x677); const x696: u32 = (@intCast(u32, x695) + @intCast(u32, x644)); var x697: u32 = undefined; var x698: u32 = undefined; fiatSecp256k1MulxU32(&x697, &x698, x7, (arg1[7])); var x699: u32 = undefined; var x700: u32 = undefined; fiatSecp256k1MulxU32(&x699, &x700, x7, (arg1[6])); var x701: u32 = undefined; var x702: u32 = undefined; fiatSecp256k1MulxU32(&x701, &x702, x7, (arg1[5])); var x703: u32 = undefined; var x704: u32 = undefined; fiatSecp256k1MulxU32(&x703, &x704, x7, (arg1[4])); var x705: u32 = undefined; var x706: u32 = undefined; fiatSecp256k1MulxU32(&x705, &x706, x7, (arg1[3])); var x707: u32 = undefined; var x708: u32 = undefined; fiatSecp256k1MulxU32(&x707, &x708, x7, (arg1[2])); var x709: u32 = undefined; var x710: u32 = undefined; fiatSecp256k1MulxU32(&x709, &x710, x7, (arg1[1])); var x711: u32 = undefined; var x712: u32 = undefined; fiatSecp256k1MulxU32(&x711, &x712, x7, (arg1[0])); var x713: u32 = undefined; var x714: u1 = undefined; fiatSecp256k1AddcarryxU32(&x713, &x714, 0x0, x712, x709); var x715: u32 = undefined; var x716: u1 = undefined; fiatSecp256k1AddcarryxU32(&x715, &x716, x714, x710, x707); var x717: u32 = undefined; var x718: u1 = undefined; fiatSecp256k1AddcarryxU32(&x717, &x718, x716, x708, x705); var x719: u32 = undefined; var x720: u1 = undefined; fiatSecp256k1AddcarryxU32(&x719, &x720, x718, x706, x703); var x721: u32 = undefined; var x722: u1 = undefined; fiatSecp256k1AddcarryxU32(&x721, &x722, x720, x704, x701); var x723: u32 = undefined; var x724: u1 = undefined; fiatSecp256k1AddcarryxU32(&x723, &x724, x722, x702, x699); var x725: u32 = undefined; var x726: u1 = undefined; fiatSecp256k1AddcarryxU32(&x725, &x726, x724, x700, x697); const x727: u32 = (@intCast(u32, x726) + x698); var x728: u32 = undefined; var x729: u1 = undefined; fiatSecp256k1AddcarryxU32(&x728, &x729, 0x0, x680, x711); var x730: u32 = undefined; var x731: u1 = undefined; fiatSecp256k1AddcarryxU32(&x730, &x731, x729, x682, x713); var x732: u32 = undefined; var x733: u1 = undefined; fiatSecp256k1AddcarryxU32(&x732, &x733, x731, x684, x715); var x734: u32 = undefined; var x735: u1 = undefined; fiatSecp256k1AddcarryxU32(&x734, &x735, x733, x686, x717); var x736: u32 = undefined; var x737: u1 = undefined; fiatSecp256k1AddcarryxU32(&x736, &x737, x735, x688, x719); var x738: u32 = undefined; var x739: u1 = undefined; fiatSecp256k1AddcarryxU32(&x738, &x739, x737, x690, x721); var x740: u32 = undefined; var x741: u1 = undefined; fiatSecp256k1AddcarryxU32(&x740, &x741, x739, x692, x723); var x742: u32 = undefined; var x743: u1 = undefined; fiatSecp256k1AddcarryxU32(&x742, &x743, x741, x694, x725); var x744: u32 = undefined; var x745: u1 = undefined; fiatSecp256k1AddcarryxU32(&x744, &x745, x743, x696, x727); var x746: u32 = undefined; var x747: u32 = undefined; fiatSecp256k1MulxU32(&x746, &x747, x728, 0xd2253531); var x748: u32 = undefined; var x749: u32 = undefined; fiatSecp256k1MulxU32(&x748, &x749, x746, 0xffffffff); var x750: u32 = undefined; var x751: u32 = undefined; fiatSecp256k1MulxU32(&x750, &x751, x746, 0xffffffff); var x752: u32 = undefined; var x753: u32 = undefined; fiatSecp256k1MulxU32(&x752, &x753, x746, 0xffffffff); var x754: u32 = undefined; var x755: u32 = undefined; fiatSecp256k1MulxU32(&x754, &x755, x746, 0xffffffff); var x756: u32 = undefined; var x757: u32 = undefined; fiatSecp256k1MulxU32(&x756, &x757, x746, 0xffffffff); var x758: u32 = undefined; var x759: u32 = undefined; fiatSecp256k1MulxU32(&x758, &x759, x746, 0xffffffff); var x760: u32 = undefined; var x761: u32 = undefined; fiatSecp256k1MulxU32(&x760, &x761, x746, 0xfffffffe); var x762: u32 = undefined; var x763: u32 = undefined; fiatSecp256k1MulxU32(&x762, &x763, x746, 0xfffffc2f); var x764: u32 = undefined; var x765: u1 = undefined; fiatSecp256k1AddcarryxU32(&x764, &x765, 0x0, x763, x760); var x766: u32 = undefined; var x767: u1 = undefined; fiatSecp256k1AddcarryxU32(&x766, &x767, x765, x761, x758); var x768: u32 = undefined; var x769: u1 = undefined; fiatSecp256k1AddcarryxU32(&x768, &x769, x767, x759, x756); var x770: u32 = undefined; var x771: u1 = undefined; fiatSecp256k1AddcarryxU32(&x770, &x771, x769, x757, x754); var x772: u32 = undefined; var x773: u1 = undefined; fiatSecp256k1AddcarryxU32(&x772, &x773, x771, x755, x752); var x774: u32 = undefined; var x775: u1 = undefined; fiatSecp256k1AddcarryxU32(&x774, &x775, x773, x753, x750); var x776: u32 = undefined; var x777: u1 = undefined; fiatSecp256k1AddcarryxU32(&x776, &x777, x775, x751, x748); const x778: u32 = (@intCast(u32, x777) + x749); var x779: u32 = undefined; var x780: u1 = undefined; fiatSecp256k1AddcarryxU32(&x779, &x780, 0x0, x728, x762); var x781: u32 = undefined; var x782: u1 = undefined; fiatSecp256k1AddcarryxU32(&x781, &x782, x780, x730, x764); var x783: u32 = undefined; var x784: u1 = undefined; fiatSecp256k1AddcarryxU32(&x783, &x784, x782, x732, x766); var x785: u32 = undefined; var x786: u1 = undefined; fiatSecp256k1AddcarryxU32(&x785, &x786, x784, x734, x768); var x787: u32 = undefined; var x788: u1 = undefined; fiatSecp256k1AddcarryxU32(&x787, &x788, x786, x736, x770); var x789: u32 = undefined; var x790: u1 = undefined; fiatSecp256k1AddcarryxU32(&x789, &x790, x788, x738, x772); var x791: u32 = undefined; var x792: u1 = undefined; fiatSecp256k1AddcarryxU32(&x791, &x792, x790, x740, x774); var x793: u32 = undefined; var x794: u1 = undefined; fiatSecp256k1AddcarryxU32(&x793, &x794, x792, x742, x776); var x795: u32 = undefined; var x796: u1 = undefined; fiatSecp256k1AddcarryxU32(&x795, &x796, x794, x744, x778); const x797: u32 = (@intCast(u32, x796) + @intCast(u32, x745)); var x798: u32 = undefined; var x799: u1 = undefined; fiatSecp256k1SubborrowxU32(&x798, &x799, 0x0, x781, 0xfffffc2f); var x800: u32 = undefined; var x801: u1 = undefined; fiatSecp256k1SubborrowxU32(&x800, &x801, x799, x783, 0xfffffffe); var x802: u32 = undefined; var x803: u1 = undefined; fiatSecp256k1SubborrowxU32(&x802, &x803, x801, x785, 0xffffffff); var x804: u32 = undefined; var x805: u1 = undefined; fiatSecp256k1SubborrowxU32(&x804, &x805, x803, x787, 0xffffffff); var x806: u32 = undefined; var x807: u1 = undefined; fiatSecp256k1SubborrowxU32(&x806, &x807, x805, x789, 0xffffffff); var x808: u32 = undefined; var x809: u1 = undefined; fiatSecp256k1SubborrowxU32(&x808, &x809, x807, x791, 0xffffffff); var x810: u32 = undefined; var x811: u1 = undefined; fiatSecp256k1SubborrowxU32(&x810, &x811, x809, x793, 0xffffffff); var x812: u32 = undefined; var x813: u1 = undefined; fiatSecp256k1SubborrowxU32(&x812, &x813, x811, x795, 0xffffffff); var x814: u32 = undefined; var x815: u1 = undefined; fiatSecp256k1SubborrowxU32(&x814, &x815, x813, x797, @intCast(u32, 0x0)); var x816: u32 = undefined; fiatSecp256k1CmovznzU32(&x816, x815, x798, x781); var x817: u32 = undefined; fiatSecp256k1CmovznzU32(&x817, x815, x800, x783); var x818: u32 = undefined; fiatSecp256k1CmovznzU32(&x818, x815, x802, x785); var x819: u32 = undefined; fiatSecp256k1CmovznzU32(&x819, x815, x804, x787); var x820: u32 = undefined; fiatSecp256k1CmovznzU32(&x820, x815, x806, x789); var x821: u32 = undefined; fiatSecp256k1CmovznzU32(&x821, x815, x808, x791); var x822: u32 = undefined; fiatSecp256k1CmovznzU32(&x822, x815, x810, x793); var x823: u32 = undefined; fiatSecp256k1CmovznzU32(&x823, x815, x812, x795); out1[0] = x816; out1[1] = x817; out1[2] = x818; out1[3] = x819; out1[4] = x820; out1[5] = x821; out1[6] = x822; out1[7] = x823; } /// The function fiatSecp256k1Add adds two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Add(out1: *[8]u32, arg1: [8]u32, arg2: [8]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatSecp256k1AddcarryxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u32 = undefined; var x4: u1 = undefined; fiatSecp256k1AddcarryxU32(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u32 = undefined; var x6: u1 = undefined; fiatSecp256k1AddcarryxU32(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u32 = undefined; var x8: u1 = undefined; fiatSecp256k1AddcarryxU32(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u32 = undefined; var x10: u1 = undefined; fiatSecp256k1AddcarryxU32(&x9, &x10, x8, (arg1[4]), (arg2[4])); var x11: u32 = undefined; var x12: u1 = undefined; fiatSecp256k1AddcarryxU32(&x11, &x12, x10, (arg1[5]), (arg2[5])); var x13: u32 = undefined; var x14: u1 = undefined; fiatSecp256k1AddcarryxU32(&x13, &x14, x12, (arg1[6]), (arg2[6])); var x15: u32 = undefined; var x16: u1 = undefined; fiatSecp256k1AddcarryxU32(&x15, &x16, x14, (arg1[7]), (arg2[7])); var x17: u32 = undefined; var x18: u1 = undefined; fiatSecp256k1SubborrowxU32(&x17, &x18, 0x0, x1, 0xfffffc2f); var x19: u32 = undefined; var x20: u1 = undefined; fiatSecp256k1SubborrowxU32(&x19, &x20, x18, x3, 0xfffffffe); var x21: u32 = undefined; var x22: u1 = undefined; fiatSecp256k1SubborrowxU32(&x21, &x22, x20, x5, 0xffffffff); var x23: u32 = undefined; var x24: u1 = undefined; fiatSecp256k1SubborrowxU32(&x23, &x24, x22, x7, 0xffffffff); var x25: u32 = undefined; var x26: u1 = undefined; fiatSecp256k1SubborrowxU32(&x25, &x26, x24, x9, 0xffffffff); var x27: u32 = undefined; var x28: u1 = undefined; fiatSecp256k1SubborrowxU32(&x27, &x28, x26, x11, 0xffffffff); var x29: u32 = undefined; var x30: u1 = undefined; fiatSecp256k1SubborrowxU32(&x29, &x30, x28, x13, 0xffffffff); var x31: u32 = undefined; var x32: u1 = undefined; fiatSecp256k1SubborrowxU32(&x31, &x32, x30, x15, 0xffffffff); var x33: u32 = undefined; var x34: u1 = undefined; fiatSecp256k1SubborrowxU32(&x33, &x34, x32, @intCast(u32, x16), @intCast(u32, 0x0)); var x35: u32 = undefined; fiatSecp256k1CmovznzU32(&x35, x34, x17, x1); var x36: u32 = undefined; fiatSecp256k1CmovznzU32(&x36, x34, x19, x3); var x37: u32 = undefined; fiatSecp256k1CmovznzU32(&x37, x34, x21, x5); var x38: u32 = undefined; fiatSecp256k1CmovznzU32(&x38, x34, x23, x7); var x39: u32 = undefined; fiatSecp256k1CmovznzU32(&x39, x34, x25, x9); var x40: u32 = undefined; fiatSecp256k1CmovznzU32(&x40, x34, x27, x11); var x41: u32 = undefined; fiatSecp256k1CmovznzU32(&x41, x34, x29, x13); var x42: u32 = undefined; fiatSecp256k1CmovznzU32(&x42, x34, x31, x15); out1[0] = x35; out1[1] = x36; out1[2] = x37; out1[3] = x38; out1[4] = x39; out1[5] = x40; out1[6] = x41; out1[7] = x42; } /// The function fiatSecp256k1Sub subtracts two field elements in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Sub(out1: *[8]u32, arg1: [8]u32, arg2: [8]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatSecp256k1SubborrowxU32(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u32 = undefined; var x4: u1 = undefined; fiatSecp256k1SubborrowxU32(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u32 = undefined; var x6: u1 = undefined; fiatSecp256k1SubborrowxU32(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u32 = undefined; var x8: u1 = undefined; fiatSecp256k1SubborrowxU32(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u32 = undefined; var x10: u1 = undefined; fiatSecp256k1SubborrowxU32(&x9, &x10, x8, (arg1[4]), (arg2[4])); var x11: u32 = undefined; var x12: u1 = undefined; fiatSecp256k1SubborrowxU32(&x11, &x12, x10, (arg1[5]), (arg2[5])); var x13: u32 = undefined; var x14: u1 = undefined; fiatSecp256k1SubborrowxU32(&x13, &x14, x12, (arg1[6]), (arg2[6])); var x15: u32 = undefined; var x16: u1 = undefined; fiatSecp256k1SubborrowxU32(&x15, &x16, x14, (arg1[7]), (arg2[7])); var x17: u32 = undefined; fiatSecp256k1CmovznzU32(&x17, x16, @intCast(u32, 0x0), 0xffffffff); var x18: u32 = undefined; var x19: u1 = undefined; fiatSecp256k1AddcarryxU32(&x18, &x19, 0x0, x1, (x17 & 0xfffffc2f)); var x20: u32 = undefined; var x21: u1 = undefined; fiatSecp256k1AddcarryxU32(&x20, &x21, x19, x3, (x17 & 0xfffffffe)); var x22: u32 = undefined; var x23: u1 = undefined; fiatSecp256k1AddcarryxU32(&x22, &x23, x21, x5, x17); var x24: u32 = undefined; var x25: u1 = undefined; fiatSecp256k1AddcarryxU32(&x24, &x25, x23, x7, x17); var x26: u32 = undefined; var x27: u1 = undefined; fiatSecp256k1AddcarryxU32(&x26, &x27, x25, x9, x17); var x28: u32 = undefined; var x29: u1 = undefined; fiatSecp256k1AddcarryxU32(&x28, &x29, x27, x11, x17); var x30: u32 = undefined; var x31: u1 = undefined; fiatSecp256k1AddcarryxU32(&x30, &x31, x29, x13, x17); var x32: u32 = undefined; var x33: u1 = undefined; fiatSecp256k1AddcarryxU32(&x32, &x33, x31, x15, x17); out1[0] = x18; out1[1] = x20; out1[2] = x22; out1[3] = x24; out1[4] = x26; out1[5] = x28; out1[6] = x30; out1[7] = x32; } /// The function fiatSecp256k1Opp negates a field element in the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Opp(out1: *[8]u32, arg1: [8]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatSecp256k1SubborrowxU32(&x1, &x2, 0x0, @intCast(u32, 0x0), (arg1[0])); var x3: u32 = undefined; var x4: u1 = undefined; fiatSecp256k1SubborrowxU32(&x3, &x4, x2, @intCast(u32, 0x0), (arg1[1])); var x5: u32 = undefined; var x6: u1 = undefined; fiatSecp256k1SubborrowxU32(&x5, &x6, x4, @intCast(u32, 0x0), (arg1[2])); var x7: u32 = undefined; var x8: u1 = undefined; fiatSecp256k1SubborrowxU32(&x7, &x8, x6, @intCast(u32, 0x0), (arg1[3])); var x9: u32 = undefined; var x10: u1 = undefined; fiatSecp256k1SubborrowxU32(&x9, &x10, x8, @intCast(u32, 0x0), (arg1[4])); var x11: u32 = undefined; var x12: u1 = undefined; fiatSecp256k1SubborrowxU32(&x11, &x12, x10, @intCast(u32, 0x0), (arg1[5])); var x13: u32 = undefined; var x14: u1 = undefined; fiatSecp256k1SubborrowxU32(&x13, &x14, x12, @intCast(u32, 0x0), (arg1[6])); var x15: u32 = undefined; var x16: u1 = undefined; fiatSecp256k1SubborrowxU32(&x15, &x16, x14, @intCast(u32, 0x0), (arg1[7])); var x17: u32 = undefined; fiatSecp256k1CmovznzU32(&x17, x16, @intCast(u32, 0x0), 0xffffffff); var x18: u32 = undefined; var x19: u1 = undefined; fiatSecp256k1AddcarryxU32(&x18, &x19, 0x0, x1, (x17 & 0xfffffc2f)); var x20: u32 = undefined; var x21: u1 = undefined; fiatSecp256k1AddcarryxU32(&x20, &x21, x19, x3, (x17 & 0xfffffffe)); var x22: u32 = undefined; var x23: u1 = undefined; fiatSecp256k1AddcarryxU32(&x22, &x23, x21, x5, x17); var x24: u32 = undefined; var x25: u1 = undefined; fiatSecp256k1AddcarryxU32(&x24, &x25, x23, x7, x17); var x26: u32 = undefined; var x27: u1 = undefined; fiatSecp256k1AddcarryxU32(&x26, &x27, x25, x9, x17); var x28: u32 = undefined; var x29: u1 = undefined; fiatSecp256k1AddcarryxU32(&x28, &x29, x27, x11, x17); var x30: u32 = undefined; var x31: u1 = undefined; fiatSecp256k1AddcarryxU32(&x30, &x31, x29, x13, x17); var x32: u32 = undefined; var x33: u1 = undefined; fiatSecp256k1AddcarryxU32(&x32, &x33, x31, x15, x17); out1[0] = x18; out1[1] = x20; out1[2] = x22; out1[3] = x24; out1[4] = x26; out1[5] = x28; out1[6] = x30; out1[7] = x32; } /// The function fiatSecp256k1FromMontgomery translates a field element out of the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^32)⁻¹ mod m)^8) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1FromMontgomery(out1: *[8]u32, arg1: [8]u32) void { const x1: u32 = (arg1[0]); var x2: u32 = undefined; var x3: u32 = undefined; fiatSecp256k1MulxU32(&x2, &x3, x1, 0xd2253531); var x4: u32 = undefined; var x5: u32 = undefined; fiatSecp256k1MulxU32(&x4, &x5, x2, 0xffffffff); var x6: u32 = undefined; var x7: u32 = undefined; fiatSecp256k1MulxU32(&x6, &x7, x2, 0xffffffff); var x8: u32 = undefined; var x9: u32 = undefined; fiatSecp256k1MulxU32(&x8, &x9, x2, 0xffffffff); var x10: u32 = undefined; var x11: u32 = undefined; fiatSecp256k1MulxU32(&x10, &x11, x2, 0xffffffff); var x12: u32 = undefined; var x13: u32 = undefined; fiatSecp256k1MulxU32(&x12, &x13, x2, 0xffffffff); var x14: u32 = undefined; var x15: u32 = undefined; fiatSecp256k1MulxU32(&x14, &x15, x2, 0xffffffff); var x16: u32 = undefined; var x17: u32 = undefined; fiatSecp256k1MulxU32(&x16, &x17, x2, 0xfffffffe); var x18: u32 = undefined; var x19: u32 = undefined; fiatSecp256k1MulxU32(&x18, &x19, x2, 0xfffffc2f); var x20: u32 = undefined; var x21: u1 = undefined; fiatSecp256k1AddcarryxU32(&x20, &x21, 0x0, x19, x16); var x22: u32 = undefined; var x23: u1 = undefined; fiatSecp256k1AddcarryxU32(&x22, &x23, x21, x17, x14); var x24: u32 = undefined; var x25: u1 = undefined; fiatSecp256k1AddcarryxU32(&x24, &x25, x23, x15, x12); var x26: u32 = undefined; var x27: u1 = undefined; fiatSecp256k1AddcarryxU32(&x26, &x27, x25, x13, x10); var x28: u32 = undefined; var x29: u1 = undefined; fiatSecp256k1AddcarryxU32(&x28, &x29, x27, x11, x8); var x30: u32 = undefined; var x31: u1 = undefined; fiatSecp256k1AddcarryxU32(&x30, &x31, x29, x9, x6); var x32: u32 = undefined; var x33: u1 = undefined; fiatSecp256k1AddcarryxU32(&x32, &x33, x31, x7, x4); var x34: u32 = undefined; var x35: u1 = undefined; fiatSecp256k1AddcarryxU32(&x34, &x35, 0x0, x1, x18); var x36: u32 = undefined; var x37: u1 = undefined; fiatSecp256k1AddcarryxU32(&x36, &x37, x35, @intCast(u32, 0x0), x20); var x38: u32 = undefined; var x39: u1 = undefined; fiatSecp256k1AddcarryxU32(&x38, &x39, x37, @intCast(u32, 0x0), x22); var x40: u32 = undefined; var x41: u1 = undefined; fiatSecp256k1AddcarryxU32(&x40, &x41, x39, @intCast(u32, 0x0), x24); var x42: u32 = undefined; var x43: u1 = undefined; fiatSecp256k1AddcarryxU32(&x42, &x43, x41, @intCast(u32, 0x0), x26); var x44: u32 = undefined; var x45: u1 = undefined; fiatSecp256k1AddcarryxU32(&x44, &x45, x43, @intCast(u32, 0x0), x28); var x46: u32 = undefined; var x47: u1 = undefined; fiatSecp256k1AddcarryxU32(&x46, &x47, x45, @intCast(u32, 0x0), x30); var x48: u32 = undefined; var x49: u1 = undefined; fiatSecp256k1AddcarryxU32(&x48, &x49, x47, @intCast(u32, 0x0), x32); var x50: u32 = undefined; var x51: u1 = undefined; fiatSecp256k1AddcarryxU32(&x50, &x51, x49, @intCast(u32, 0x0), (@intCast(u32, x33) + x5)); var x52: u32 = undefined; var x53: u1 = undefined; fiatSecp256k1AddcarryxU32(&x52, &x53, 0x0, x36, (arg1[1])); var x54: u32 = undefined; var x55: u1 = undefined; fiatSecp256k1AddcarryxU32(&x54, &x55, x53, x38, @intCast(u32, 0x0)); var x56: u32 = undefined; var x57: u1 = undefined; fiatSecp256k1AddcarryxU32(&x56, &x57, x55, x40, @intCast(u32, 0x0)); var x58: u32 = undefined; var x59: u1 = undefined; fiatSecp256k1AddcarryxU32(&x58, &x59, x57, x42, @intCast(u32, 0x0)); var x60: u32 = undefined; var x61: u1 = undefined; fiatSecp256k1AddcarryxU32(&x60, &x61, x59, x44, @intCast(u32, 0x0)); var x62: u32 = undefined; var x63: u1 = undefined; fiatSecp256k1AddcarryxU32(&x62, &x63, x61, x46, @intCast(u32, 0x0)); var x64: u32 = undefined; var x65: u1 = undefined; fiatSecp256k1AddcarryxU32(&x64, &x65, x63, x48, @intCast(u32, 0x0)); var x66: u32 = undefined; var x67: u1 = undefined; fiatSecp256k1AddcarryxU32(&x66, &x67, x65, x50, @intCast(u32, 0x0)); var x68: u32 = undefined; var x69: u32 = undefined; fiatSecp256k1MulxU32(&x68, &x69, x52, 0xd2253531); var x70: u32 = undefined; var x71: u32 = undefined; fiatSecp256k1MulxU32(&x70, &x71, x68, 0xffffffff); var x72: u32 = undefined; var x73: u32 = undefined; fiatSecp256k1MulxU32(&x72, &x73, x68, 0xffffffff); var x74: u32 = undefined; var x75: u32 = undefined; fiatSecp256k1MulxU32(&x74, &x75, x68, 0xffffffff); var x76: u32 = undefined; var x77: u32 = undefined; fiatSecp256k1MulxU32(&x76, &x77, x68, 0xffffffff); var x78: u32 = undefined; var x79: u32 = undefined; fiatSecp256k1MulxU32(&x78, &x79, x68, 0xffffffff); var x80: u32 = undefined; var x81: u32 = undefined; fiatSecp256k1MulxU32(&x80, &x81, x68, 0xffffffff); var x82: u32 = undefined; var x83: u32 = undefined; fiatSecp256k1MulxU32(&x82, &x83, x68, 0xfffffffe); var x84: u32 = undefined; var x85: u32 = undefined; fiatSecp256k1MulxU32(&x84, &x85, x68, 0xfffffc2f); var x86: u32 = undefined; var x87: u1 = undefined; fiatSecp256k1AddcarryxU32(&x86, &x87, 0x0, x85, x82); var x88: u32 = undefined; var x89: u1 = undefined; fiatSecp256k1AddcarryxU32(&x88, &x89, x87, x83, x80); var x90: u32 = undefined; var x91: u1 = undefined; fiatSecp256k1AddcarryxU32(&x90, &x91, x89, x81, x78); var x92: u32 = undefined; var x93: u1 = undefined; fiatSecp256k1AddcarryxU32(&x92, &x93, x91, x79, x76); var x94: u32 = undefined; var x95: u1 = undefined; fiatSecp256k1AddcarryxU32(&x94, &x95, x93, x77, x74); var x96: u32 = undefined; var x97: u1 = undefined; fiatSecp256k1AddcarryxU32(&x96, &x97, x95, x75, x72); var x98: u32 = undefined; var x99: u1 = undefined; fiatSecp256k1AddcarryxU32(&x98, &x99, x97, x73, x70); var x100: u32 = undefined; var x101: u1 = undefined; fiatSecp256k1AddcarryxU32(&x100, &x101, 0x0, x52, x84); var x102: u32 = undefined; var x103: u1 = undefined; fiatSecp256k1AddcarryxU32(&x102, &x103, x101, x54, x86); var x104: u32 = undefined; var x105: u1 = undefined; fiatSecp256k1AddcarryxU32(&x104, &x105, x103, x56, x88); var x106: u32 = undefined; var x107: u1 = undefined; fiatSecp256k1AddcarryxU32(&x106, &x107, x105, x58, x90); var x108: u32 = undefined; var x109: u1 = undefined; fiatSecp256k1AddcarryxU32(&x108, &x109, x107, x60, x92); var x110: u32 = undefined; var x111: u1 = undefined; fiatSecp256k1AddcarryxU32(&x110, &x111, x109, x62, x94); var x112: u32 = undefined; var x113: u1 = undefined; fiatSecp256k1AddcarryxU32(&x112, &x113, x111, x64, x96); var x114: u32 = undefined; var x115: u1 = undefined; fiatSecp256k1AddcarryxU32(&x114, &x115, x113, x66, x98); var x116: u32 = undefined; var x117: u1 = undefined; fiatSecp256k1AddcarryxU32(&x116, &x117, x115, (@intCast(u32, x67) + @intCast(u32, x51)), (@intCast(u32, x99) + x71)); var x118: u32 = undefined; var x119: u1 = undefined; fiatSecp256k1AddcarryxU32(&x118, &x119, 0x0, x102, (arg1[2])); var x120: u32 = undefined; var x121: u1 = undefined; fiatSecp256k1AddcarryxU32(&x120, &x121, x119, x104, @intCast(u32, 0x0)); var x122: u32 = undefined; var x123: u1 = undefined; fiatSecp256k1AddcarryxU32(&x122, &x123, x121, x106, @intCast(u32, 0x0)); var x124: u32 = undefined; var x125: u1 = undefined; fiatSecp256k1AddcarryxU32(&x124, &x125, x123, x108, @intCast(u32, 0x0)); var x126: u32 = undefined; var x127: u1 = undefined; fiatSecp256k1AddcarryxU32(&x126, &x127, x125, x110, @intCast(u32, 0x0)); var x128: u32 = undefined; var x129: u1 = undefined; fiatSecp256k1AddcarryxU32(&x128, &x129, x127, x112, @intCast(u32, 0x0)); var x130: u32 = undefined; var x131: u1 = undefined; fiatSecp256k1AddcarryxU32(&x130, &x131, x129, x114, @intCast(u32, 0x0)); var x132: u32 = undefined; var x133: u1 = undefined; fiatSecp256k1AddcarryxU32(&x132, &x133, x131, x116, @intCast(u32, 0x0)); var x134: u32 = undefined; var x135: u32 = undefined; fiatSecp256k1MulxU32(&x134, &x135, x118, 0xd2253531); var x136: u32 = undefined; var x137: u32 = undefined; fiatSecp256k1MulxU32(&x136, &x137, x134, 0xffffffff); var x138: u32 = undefined; var x139: u32 = undefined; fiatSecp256k1MulxU32(&x138, &x139, x134, 0xffffffff); var x140: u32 = undefined; var x141: u32 = undefined; fiatSecp256k1MulxU32(&x140, &x141, x134, 0xffffffff); var x142: u32 = undefined; var x143: u32 = undefined; fiatSecp256k1MulxU32(&x142, &x143, x134, 0xffffffff); var x144: u32 = undefined; var x145: u32 = undefined; fiatSecp256k1MulxU32(&x144, &x145, x134, 0xffffffff); var x146: u32 = undefined; var x147: u32 = undefined; fiatSecp256k1MulxU32(&x146, &x147, x134, 0xffffffff); var x148: u32 = undefined; var x149: u32 = undefined; fiatSecp256k1MulxU32(&x148, &x149, x134, 0xfffffffe); var x150: u32 = undefined; var x151: u32 = undefined; fiatSecp256k1MulxU32(&x150, &x151, x134, 0xfffffc2f); var x152: u32 = undefined; var x153: u1 = undefined; fiatSecp256k1AddcarryxU32(&x152, &x153, 0x0, x151, x148); var x154: u32 = undefined; var x155: u1 = undefined; fiatSecp256k1AddcarryxU32(&x154, &x155, x153, x149, x146); var x156: u32 = undefined; var x157: u1 = undefined; fiatSecp256k1AddcarryxU32(&x156, &x157, x155, x147, x144); var x158: u32 = undefined; var x159: u1 = undefined; fiatSecp256k1AddcarryxU32(&x158, &x159, x157, x145, x142); var x160: u32 = undefined; var x161: u1 = undefined; fiatSecp256k1AddcarryxU32(&x160, &x161, x159, x143, x140); var x162: u32 = undefined; var x163: u1 = undefined; fiatSecp256k1AddcarryxU32(&x162, &x163, x161, x141, x138); var x164: u32 = undefined; var x165: u1 = undefined; fiatSecp256k1AddcarryxU32(&x164, &x165, x163, x139, x136); var x166: u32 = undefined; var x167: u1 = undefined; fiatSecp256k1AddcarryxU32(&x166, &x167, 0x0, x118, x150); var x168: u32 = undefined; var x169: u1 = undefined; fiatSecp256k1AddcarryxU32(&x168, &x169, x167, x120, x152); var x170: u32 = undefined; var x171: u1 = undefined; fiatSecp256k1AddcarryxU32(&x170, &x171, x169, x122, x154); var x172: u32 = undefined; var x173: u1 = undefined; fiatSecp256k1AddcarryxU32(&x172, &x173, x171, x124, x156); var x174: u32 = undefined; var x175: u1 = undefined; fiatSecp256k1AddcarryxU32(&x174, &x175, x173, x126, x158); var x176: u32 = undefined; var x177: u1 = undefined; fiatSecp256k1AddcarryxU32(&x176, &x177, x175, x128, x160); var x178: u32 = undefined; var x179: u1 = undefined; fiatSecp256k1AddcarryxU32(&x178, &x179, x177, x130, x162); var x180: u32 = undefined; var x181: u1 = undefined; fiatSecp256k1AddcarryxU32(&x180, &x181, x179, x132, x164); var x182: u32 = undefined; var x183: u1 = undefined; fiatSecp256k1AddcarryxU32(&x182, &x183, x181, (@intCast(u32, x133) + @intCast(u32, x117)), (@intCast(u32, x165) + x137)); var x184: u32 = undefined; var x185: u1 = undefined; fiatSecp256k1AddcarryxU32(&x184, &x185, 0x0, x168, (arg1[3])); var x186: u32 = undefined; var x187: u1 = undefined; fiatSecp256k1AddcarryxU32(&x186, &x187, x185, x170, @intCast(u32, 0x0)); var x188: u32 = undefined; var x189: u1 = undefined; fiatSecp256k1AddcarryxU32(&x188, &x189, x187, x172, @intCast(u32, 0x0)); var x190: u32 = undefined; var x191: u1 = undefined; fiatSecp256k1AddcarryxU32(&x190, &x191, x189, x174, @intCast(u32, 0x0)); var x192: u32 = undefined; var x193: u1 = undefined; fiatSecp256k1AddcarryxU32(&x192, &x193, x191, x176, @intCast(u32, 0x0)); var x194: u32 = undefined; var x195: u1 = undefined; fiatSecp256k1AddcarryxU32(&x194, &x195, x193, x178, @intCast(u32, 0x0)); var x196: u32 = undefined; var x197: u1 = undefined; fiatSecp256k1AddcarryxU32(&x196, &x197, x195, x180, @intCast(u32, 0x0)); var x198: u32 = undefined; var x199: u1 = undefined; fiatSecp256k1AddcarryxU32(&x198, &x199, x197, x182, @intCast(u32, 0x0)); var x200: u32 = undefined; var x201: u32 = undefined; fiatSecp256k1MulxU32(&x200, &x201, x184, 0xd2253531); var x202: u32 = undefined; var x203: u32 = undefined; fiatSecp256k1MulxU32(&x202, &x203, x200, 0xffffffff); var x204: u32 = undefined; var x205: u32 = undefined; fiatSecp256k1MulxU32(&x204, &x205, x200, 0xffffffff); var x206: u32 = undefined; var x207: u32 = undefined; fiatSecp256k1MulxU32(&x206, &x207, x200, 0xffffffff); var x208: u32 = undefined; var x209: u32 = undefined; fiatSecp256k1MulxU32(&x208, &x209, x200, 0xffffffff); var x210: u32 = undefined; var x211: u32 = undefined; fiatSecp256k1MulxU32(&x210, &x211, x200, 0xffffffff); var x212: u32 = undefined; var x213: u32 = undefined; fiatSecp256k1MulxU32(&x212, &x213, x200, 0xffffffff); var x214: u32 = undefined; var x215: u32 = undefined; fiatSecp256k1MulxU32(&x214, &x215, x200, 0xfffffffe); var x216: u32 = undefined; var x217: u32 = undefined; fiatSecp256k1MulxU32(&x216, &x217, x200, 0xfffffc2f); var x218: u32 = undefined; var x219: u1 = undefined; fiatSecp256k1AddcarryxU32(&x218, &x219, 0x0, x217, x214); var x220: u32 = undefined; var x221: u1 = undefined; fiatSecp256k1AddcarryxU32(&x220, &x221, x219, x215, x212); var x222: u32 = undefined; var x223: u1 = undefined; fiatSecp256k1AddcarryxU32(&x222, &x223, x221, x213, x210); var x224: u32 = undefined; var x225: u1 = undefined; fiatSecp256k1AddcarryxU32(&x224, &x225, x223, x211, x208); var x226: u32 = undefined; var x227: u1 = undefined; fiatSecp256k1AddcarryxU32(&x226, &x227, x225, x209, x206); var x228: u32 = undefined; var x229: u1 = undefined; fiatSecp256k1AddcarryxU32(&x228, &x229, x227, x207, x204); var x230: u32 = undefined; var x231: u1 = undefined; fiatSecp256k1AddcarryxU32(&x230, &x231, x229, x205, x202); var x232: u32 = undefined; var x233: u1 = undefined; fiatSecp256k1AddcarryxU32(&x232, &x233, 0x0, x184, x216); var x234: u32 = undefined; var x235: u1 = undefined; fiatSecp256k1AddcarryxU32(&x234, &x235, x233, x186, x218); var x236: u32 = undefined; var x237: u1 = undefined; fiatSecp256k1AddcarryxU32(&x236, &x237, x235, x188, x220); var x238: u32 = undefined; var x239: u1 = undefined; fiatSecp256k1AddcarryxU32(&x238, &x239, x237, x190, x222); var x240: u32 = undefined; var x241: u1 = undefined; fiatSecp256k1AddcarryxU32(&x240, &x241, x239, x192, x224); var x242: u32 = undefined; var x243: u1 = undefined; fiatSecp256k1AddcarryxU32(&x242, &x243, x241, x194, x226); var x244: u32 = undefined; var x245: u1 = undefined; fiatSecp256k1AddcarryxU32(&x244, &x245, x243, x196, x228); var x246: u32 = undefined; var x247: u1 = undefined; fiatSecp256k1AddcarryxU32(&x246, &x247, x245, x198, x230); var x248: u32 = undefined; var x249: u1 = undefined; fiatSecp256k1AddcarryxU32(&x248, &x249, x247, (@intCast(u32, x199) + @intCast(u32, x183)), (@intCast(u32, x231) + x203)); var x250: u32 = undefined; var x251: u1 = undefined; fiatSecp256k1AddcarryxU32(&x250, &x251, 0x0, x234, (arg1[4])); var x252: u32 = undefined; var x253: u1 = undefined; fiatSecp256k1AddcarryxU32(&x252, &x253, x251, x236, @intCast(u32, 0x0)); var x254: u32 = undefined; var x255: u1 = undefined; fiatSecp256k1AddcarryxU32(&x254, &x255, x253, x238, @intCast(u32, 0x0)); var x256: u32 = undefined; var x257: u1 = undefined; fiatSecp256k1AddcarryxU32(&x256, &x257, x255, x240, @intCast(u32, 0x0)); var x258: u32 = undefined; var x259: u1 = undefined; fiatSecp256k1AddcarryxU32(&x258, &x259, x257, x242, @intCast(u32, 0x0)); var x260: u32 = undefined; var x261: u1 = undefined; fiatSecp256k1AddcarryxU32(&x260, &x261, x259, x244, @intCast(u32, 0x0)); var x262: u32 = undefined; var x263: u1 = undefined; fiatSecp256k1AddcarryxU32(&x262, &x263, x261, x246, @intCast(u32, 0x0)); var x264: u32 = undefined; var x265: u1 = undefined; fiatSecp256k1AddcarryxU32(&x264, &x265, x263, x248, @intCast(u32, 0x0)); var x266: u32 = undefined; var x267: u32 = undefined; fiatSecp256k1MulxU32(&x266, &x267, x250, 0xd2253531); var x268: u32 = undefined; var x269: u32 = undefined; fiatSecp256k1MulxU32(&x268, &x269, x266, 0xffffffff); var x270: u32 = undefined; var x271: u32 = undefined; fiatSecp256k1MulxU32(&x270, &x271, x266, 0xffffffff); var x272: u32 = undefined; var x273: u32 = undefined; fiatSecp256k1MulxU32(&x272, &x273, x266, 0xffffffff); var x274: u32 = undefined; var x275: u32 = undefined; fiatSecp256k1MulxU32(&x274, &x275, x266, 0xffffffff); var x276: u32 = undefined; var x277: u32 = undefined; fiatSecp256k1MulxU32(&x276, &x277, x266, 0xffffffff); var x278: u32 = undefined; var x279: u32 = undefined; fiatSecp256k1MulxU32(&x278, &x279, x266, 0xffffffff); var x280: u32 = undefined; var x281: u32 = undefined; fiatSecp256k1MulxU32(&x280, &x281, x266, 0xfffffffe); var x282: u32 = undefined; var x283: u32 = undefined; fiatSecp256k1MulxU32(&x282, &x283, x266, 0xfffffc2f); var x284: u32 = undefined; var x285: u1 = undefined; fiatSecp256k1AddcarryxU32(&x284, &x285, 0x0, x283, x280); var x286: u32 = undefined; var x287: u1 = undefined; fiatSecp256k1AddcarryxU32(&x286, &x287, x285, x281, x278); var x288: u32 = undefined; var x289: u1 = undefined; fiatSecp256k1AddcarryxU32(&x288, &x289, x287, x279, x276); var x290: u32 = undefined; var x291: u1 = undefined; fiatSecp256k1AddcarryxU32(&x290, &x291, x289, x277, x274); var x292: u32 = undefined; var x293: u1 = undefined; fiatSecp256k1AddcarryxU32(&x292, &x293, x291, x275, x272); var x294: u32 = undefined; var x295: u1 = undefined; fiatSecp256k1AddcarryxU32(&x294, &x295, x293, x273, x270); var x296: u32 = undefined; var x297: u1 = undefined; fiatSecp256k1AddcarryxU32(&x296, &x297, x295, x271, x268); var x298: u32 = undefined; var x299: u1 = undefined; fiatSecp256k1AddcarryxU32(&x298, &x299, 0x0, x250, x282); var x300: u32 = undefined; var x301: u1 = undefined; fiatSecp256k1AddcarryxU32(&x300, &x301, x299, x252, x284); var x302: u32 = undefined; var x303: u1 = undefined; fiatSecp256k1AddcarryxU32(&x302, &x303, x301, x254, x286); var x304: u32 = undefined; var x305: u1 = undefined; fiatSecp256k1AddcarryxU32(&x304, &x305, x303, x256, x288); var x306: u32 = undefined; var x307: u1 = undefined; fiatSecp256k1AddcarryxU32(&x306, &x307, x305, x258, x290); var x308: u32 = undefined; var x309: u1 = undefined; fiatSecp256k1AddcarryxU32(&x308, &x309, x307, x260, x292); var x310: u32 = undefined; var x311: u1 = undefined; fiatSecp256k1AddcarryxU32(&x310, &x311, x309, x262, x294); var x312: u32 = undefined; var x313: u1 = undefined; fiatSecp256k1AddcarryxU32(&x312, &x313, x311, x264, x296); var x314: u32 = undefined; var x315: u1 = undefined; fiatSecp256k1AddcarryxU32(&x314, &x315, x313, (@intCast(u32, x265) + @intCast(u32, x249)), (@intCast(u32, x297) + x269)); var x316: u32 = undefined; var x317: u1 = undefined; fiatSecp256k1AddcarryxU32(&x316, &x317, 0x0, x300, (arg1[5])); var x318: u32 = undefined; var x319: u1 = undefined; fiatSecp256k1AddcarryxU32(&x318, &x319, x317, x302, @intCast(u32, 0x0)); var x320: u32 = undefined; var x321: u1 = undefined; fiatSecp256k1AddcarryxU32(&x320, &x321, x319, x304, @intCast(u32, 0x0)); var x322: u32 = undefined; var x323: u1 = undefined; fiatSecp256k1AddcarryxU32(&x322, &x323, x321, x306, @intCast(u32, 0x0)); var x324: u32 = undefined; var x325: u1 = undefined; fiatSecp256k1AddcarryxU32(&x324, &x325, x323, x308, @intCast(u32, 0x0)); var x326: u32 = undefined; var x327: u1 = undefined; fiatSecp256k1AddcarryxU32(&x326, &x327, x325, x310, @intCast(u32, 0x0)); var x328: u32 = undefined; var x329: u1 = undefined; fiatSecp256k1AddcarryxU32(&x328, &x329, x327, x312, @intCast(u32, 0x0)); var x330: u32 = undefined; var x331: u1 = undefined; fiatSecp256k1AddcarryxU32(&x330, &x331, x329, x314, @intCast(u32, 0x0)); var x332: u32 = undefined; var x333: u32 = undefined; fiatSecp256k1MulxU32(&x332, &x333, x316, 0xd2253531); var x334: u32 = undefined; var x335: u32 = undefined; fiatSecp256k1MulxU32(&x334, &x335, x332, 0xffffffff); var x336: u32 = undefined; var x337: u32 = undefined; fiatSecp256k1MulxU32(&x336, &x337, x332, 0xffffffff); var x338: u32 = undefined; var x339: u32 = undefined; fiatSecp256k1MulxU32(&x338, &x339, x332, 0xffffffff); var x340: u32 = undefined; var x341: u32 = undefined; fiatSecp256k1MulxU32(&x340, &x341, x332, 0xffffffff); var x342: u32 = undefined; var x343: u32 = undefined; fiatSecp256k1MulxU32(&x342, &x343, x332, 0xffffffff); var x344: u32 = undefined; var x345: u32 = undefined; fiatSecp256k1MulxU32(&x344, &x345, x332, 0xffffffff); var x346: u32 = undefined; var x347: u32 = undefined; fiatSecp256k1MulxU32(&x346, &x347, x332, 0xfffffffe); var x348: u32 = undefined; var x349: u32 = undefined; fiatSecp256k1MulxU32(&x348, &x349, x332, 0xfffffc2f); var x350: u32 = undefined; var x351: u1 = undefined; fiatSecp256k1AddcarryxU32(&x350, &x351, 0x0, x349, x346); var x352: u32 = undefined; var x353: u1 = undefined; fiatSecp256k1AddcarryxU32(&x352, &x353, x351, x347, x344); var x354: u32 = undefined; var x355: u1 = undefined; fiatSecp256k1AddcarryxU32(&x354, &x355, x353, x345, x342); var x356: u32 = undefined; var x357: u1 = undefined; fiatSecp256k1AddcarryxU32(&x356, &x357, x355, x343, x340); var x358: u32 = undefined; var x359: u1 = undefined; fiatSecp256k1AddcarryxU32(&x358, &x359, x357, x341, x338); var x360: u32 = undefined; var x361: u1 = undefined; fiatSecp256k1AddcarryxU32(&x360, &x361, x359, x339, x336); var x362: u32 = undefined; var x363: u1 = undefined; fiatSecp256k1AddcarryxU32(&x362, &x363, x361, x337, x334); var x364: u32 = undefined; var x365: u1 = undefined; fiatSecp256k1AddcarryxU32(&x364, &x365, 0x0, x316, x348); var x366: u32 = undefined; var x367: u1 = undefined; fiatSecp256k1AddcarryxU32(&x366, &x367, x365, x318, x350); var x368: u32 = undefined; var x369: u1 = undefined; fiatSecp256k1AddcarryxU32(&x368, &x369, x367, x320, x352); var x370: u32 = undefined; var x371: u1 = undefined; fiatSecp256k1AddcarryxU32(&x370, &x371, x369, x322, x354); var x372: u32 = undefined; var x373: u1 = undefined; fiatSecp256k1AddcarryxU32(&x372, &x373, x371, x324, x356); var x374: u32 = undefined; var x375: u1 = undefined; fiatSecp256k1AddcarryxU32(&x374, &x375, x373, x326, x358); var x376: u32 = undefined; var x377: u1 = undefined; fiatSecp256k1AddcarryxU32(&x376, &x377, x375, x328, x360); var x378: u32 = undefined; var x379: u1 = undefined; fiatSecp256k1AddcarryxU32(&x378, &x379, x377, x330, x362); var x380: u32 = undefined; var x381: u1 = undefined; fiatSecp256k1AddcarryxU32(&x380, &x381, x379, (@intCast(u32, x331) + @intCast(u32, x315)), (@intCast(u32, x363) + x335)); var x382: u32 = undefined; var x383: u1 = undefined; fiatSecp256k1AddcarryxU32(&x382, &x383, 0x0, x366, (arg1[6])); var x384: u32 = undefined; var x385: u1 = undefined; fiatSecp256k1AddcarryxU32(&x384, &x385, x383, x368, @intCast(u32, 0x0)); var x386: u32 = undefined; var x387: u1 = undefined; fiatSecp256k1AddcarryxU32(&x386, &x387, x385, x370, @intCast(u32, 0x0)); var x388: u32 = undefined; var x389: u1 = undefined; fiatSecp256k1AddcarryxU32(&x388, &x389, x387, x372, @intCast(u32, 0x0)); var x390: u32 = undefined; var x391: u1 = undefined; fiatSecp256k1AddcarryxU32(&x390, &x391, x389, x374, @intCast(u32, 0x0)); var x392: u32 = undefined; var x393: u1 = undefined; fiatSecp256k1AddcarryxU32(&x392, &x393, x391, x376, @intCast(u32, 0x0)); var x394: u32 = undefined; var x395: u1 = undefined; fiatSecp256k1AddcarryxU32(&x394, &x395, x393, x378, @intCast(u32, 0x0)); var x396: u32 = undefined; var x397: u1 = undefined; fiatSecp256k1AddcarryxU32(&x396, &x397, x395, x380, @intCast(u32, 0x0)); var x398: u32 = undefined; var x399: u32 = undefined; fiatSecp256k1MulxU32(&x398, &x399, x382, 0xd2253531); var x400: u32 = undefined; var x401: u32 = undefined; fiatSecp256k1MulxU32(&x400, &x401, x398, 0xffffffff); var x402: u32 = undefined; var x403: u32 = undefined; fiatSecp256k1MulxU32(&x402, &x403, x398, 0xffffffff); var x404: u32 = undefined; var x405: u32 = undefined; fiatSecp256k1MulxU32(&x404, &x405, x398, 0xffffffff); var x406: u32 = undefined; var x407: u32 = undefined; fiatSecp256k1MulxU32(&x406, &x407, x398, 0xffffffff); var x408: u32 = undefined; var x409: u32 = undefined; fiatSecp256k1MulxU32(&x408, &x409, x398, 0xffffffff); var x410: u32 = undefined; var x411: u32 = undefined; fiatSecp256k1MulxU32(&x410, &x411, x398, 0xffffffff); var x412: u32 = undefined; var x413: u32 = undefined; fiatSecp256k1MulxU32(&x412, &x413, x398, 0xfffffffe); var x414: u32 = undefined; var x415: u32 = undefined; fiatSecp256k1MulxU32(&x414, &x415, x398, 0xfffffc2f); var x416: u32 = undefined; var x417: u1 = undefined; fiatSecp256k1AddcarryxU32(&x416, &x417, 0x0, x415, x412); var x418: u32 = undefined; var x419: u1 = undefined; fiatSecp256k1AddcarryxU32(&x418, &x419, x417, x413, x410); var x420: u32 = undefined; var x421: u1 = undefined; fiatSecp256k1AddcarryxU32(&x420, &x421, x419, x411, x408); var x422: u32 = undefined; var x423: u1 = undefined; fiatSecp256k1AddcarryxU32(&x422, &x423, x421, x409, x406); var x424: u32 = undefined; var x425: u1 = undefined; fiatSecp256k1AddcarryxU32(&x424, &x425, x423, x407, x404); var x426: u32 = undefined; var x427: u1 = undefined; fiatSecp256k1AddcarryxU32(&x426, &x427, x425, x405, x402); var x428: u32 = undefined; var x429: u1 = undefined; fiatSecp256k1AddcarryxU32(&x428, &x429, x427, x403, x400); var x430: u32 = undefined; var x431: u1 = undefined; fiatSecp256k1AddcarryxU32(&x430, &x431, 0x0, x382, x414); var x432: u32 = undefined; var x433: u1 = undefined; fiatSecp256k1AddcarryxU32(&x432, &x433, x431, x384, x416); var x434: u32 = undefined; var x435: u1 = undefined; fiatSecp256k1AddcarryxU32(&x434, &x435, x433, x386, x418); var x436: u32 = undefined; var x437: u1 = undefined; fiatSecp256k1AddcarryxU32(&x436, &x437, x435, x388, x420); var x438: u32 = undefined; var x439: u1 = undefined; fiatSecp256k1AddcarryxU32(&x438, &x439, x437, x390, x422); var x440: u32 = undefined; var x441: u1 = undefined; fiatSecp256k1AddcarryxU32(&x440, &x441, x439, x392, x424); var x442: u32 = undefined; var x443: u1 = undefined; fiatSecp256k1AddcarryxU32(&x442, &x443, x441, x394, x426); var x444: u32 = undefined; var x445: u1 = undefined; fiatSecp256k1AddcarryxU32(&x444, &x445, x443, x396, x428); var x446: u32 = undefined; var x447: u1 = undefined; fiatSecp256k1AddcarryxU32(&x446, &x447, x445, (@intCast(u32, x397) + @intCast(u32, x381)), (@intCast(u32, x429) + x401)); var x448: u32 = undefined; var x449: u1 = undefined; fiatSecp256k1AddcarryxU32(&x448, &x449, 0x0, x432, (arg1[7])); var x450: u32 = undefined; var x451: u1 = undefined; fiatSecp256k1AddcarryxU32(&x450, &x451, x449, x434, @intCast(u32, 0x0)); var x452: u32 = undefined; var x453: u1 = undefined; fiatSecp256k1AddcarryxU32(&x452, &x453, x451, x436, @intCast(u32, 0x0)); var x454: u32 = undefined; var x455: u1 = undefined; fiatSecp256k1AddcarryxU32(&x454, &x455, x453, x438, @intCast(u32, 0x0)); var x456: u32 = undefined; var x457: u1 = undefined; fiatSecp256k1AddcarryxU32(&x456, &x457, x455, x440, @intCast(u32, 0x0)); var x458: u32 = undefined; var x459: u1 = undefined; fiatSecp256k1AddcarryxU32(&x458, &x459, x457, x442, @intCast(u32, 0x0)); var x460: u32 = undefined; var x461: u1 = undefined; fiatSecp256k1AddcarryxU32(&x460, &x461, x459, x444, @intCast(u32, 0x0)); var x462: u32 = undefined; var x463: u1 = undefined; fiatSecp256k1AddcarryxU32(&x462, &x463, x461, x446, @intCast(u32, 0x0)); var x464: u32 = undefined; var x465: u32 = undefined; fiatSecp256k1MulxU32(&x464, &x465, x448, 0xd2253531); var x466: u32 = undefined; var x467: u32 = undefined; fiatSecp256k1MulxU32(&x466, &x467, x464, 0xffffffff); var x468: u32 = undefined; var x469: u32 = undefined; fiatSecp256k1MulxU32(&x468, &x469, x464, 0xffffffff); var x470: u32 = undefined; var x471: u32 = undefined; fiatSecp256k1MulxU32(&x470, &x471, x464, 0xffffffff); var x472: u32 = undefined; var x473: u32 = undefined; fiatSecp256k1MulxU32(&x472, &x473, x464, 0xffffffff); var x474: u32 = undefined; var x475: u32 = undefined; fiatSecp256k1MulxU32(&x474, &x475, x464, 0xffffffff); var x476: u32 = undefined; var x477: u32 = undefined; fiatSecp256k1MulxU32(&x476, &x477, x464, 0xffffffff); var x478: u32 = undefined; var x479: u32 = undefined; fiatSecp256k1MulxU32(&x478, &x479, x464, 0xfffffffe); var x480: u32 = undefined; var x481: u32 = undefined; fiatSecp256k1MulxU32(&x480, &x481, x464, 0xfffffc2f); var x482: u32 = undefined; var x483: u1 = undefined; fiatSecp256k1AddcarryxU32(&x482, &x483, 0x0, x481, x478); var x484: u32 = undefined; var x485: u1 = undefined; fiatSecp256k1AddcarryxU32(&x484, &x485, x483, x479, x476); var x486: u32 = undefined; var x487: u1 = undefined; fiatSecp256k1AddcarryxU32(&x486, &x487, x485, x477, x474); var x488: u32 = undefined; var x489: u1 = undefined; fiatSecp256k1AddcarryxU32(&x488, &x489, x487, x475, x472); var x490: u32 = undefined; var x491: u1 = undefined; fiatSecp256k1AddcarryxU32(&x490, &x491, x489, x473, x470); var x492: u32 = undefined; var x493: u1 = undefined; fiatSecp256k1AddcarryxU32(&x492, &x493, x491, x471, x468); var x494: u32 = undefined; var x495: u1 = undefined; fiatSecp256k1AddcarryxU32(&x494, &x495, x493, x469, x466); var x496: u32 = undefined; var x497: u1 = undefined; fiatSecp256k1AddcarryxU32(&x496, &x497, 0x0, x448, x480); var x498: u32 = undefined; var x499: u1 = undefined; fiatSecp256k1AddcarryxU32(&x498, &x499, x497, x450, x482); var x500: u32 = undefined; var x501: u1 = undefined; fiatSecp256k1AddcarryxU32(&x500, &x501, x499, x452, x484); var x502: u32 = undefined; var x503: u1 = undefined; fiatSecp256k1AddcarryxU32(&x502, &x503, x501, x454, x486); var x504: u32 = undefined; var x505: u1 = undefined; fiatSecp256k1AddcarryxU32(&x504, &x505, x503, x456, x488); var x506: u32 = undefined; var x507: u1 = undefined; fiatSecp256k1AddcarryxU32(&x506, &x507, x505, x458, x490); var x508: u32 = undefined; var x509: u1 = undefined; fiatSecp256k1AddcarryxU32(&x508, &x509, x507, x460, x492); var x510: u32 = undefined; var x511: u1 = undefined; fiatSecp256k1AddcarryxU32(&x510, &x511, x509, x462, x494); var x512: u32 = undefined; var x513: u1 = undefined; fiatSecp256k1AddcarryxU32(&x512, &x513, x511, (@intCast(u32, x463) + @intCast(u32, x447)), (@intCast(u32, x495) + x467)); var x514: u32 = undefined; var x515: u1 = undefined; fiatSecp256k1SubborrowxU32(&x514, &x515, 0x0, x498, 0xfffffc2f); var x516: u32 = undefined; var x517: u1 = undefined; fiatSecp256k1SubborrowxU32(&x516, &x517, x515, x500, 0xfffffffe); var x518: u32 = undefined; var x519: u1 = undefined; fiatSecp256k1SubborrowxU32(&x518, &x519, x517, x502, 0xffffffff); var x520: u32 = undefined; var x521: u1 = undefined; fiatSecp256k1SubborrowxU32(&x520, &x521, x519, x504, 0xffffffff); var x522: u32 = undefined; var x523: u1 = undefined; fiatSecp256k1SubborrowxU32(&x522, &x523, x521, x506, 0xffffffff); var x524: u32 = undefined; var x525: u1 = undefined; fiatSecp256k1SubborrowxU32(&x524, &x525, x523, x508, 0xffffffff); var x526: u32 = undefined; var x527: u1 = undefined; fiatSecp256k1SubborrowxU32(&x526, &x527, x525, x510, 0xffffffff); var x528: u32 = undefined; var x529: u1 = undefined; fiatSecp256k1SubborrowxU32(&x528, &x529, x527, x512, 0xffffffff); var x530: u32 = undefined; var x531: u1 = undefined; fiatSecp256k1SubborrowxU32(&x530, &x531, x529, @intCast(u32, x513), @intCast(u32, 0x0)); var x532: u32 = undefined; fiatSecp256k1CmovznzU32(&x532, x531, x514, x498); var x533: u32 = undefined; fiatSecp256k1CmovznzU32(&x533, x531, x516, x500); var x534: u32 = undefined; fiatSecp256k1CmovznzU32(&x534, x531, x518, x502); var x535: u32 = undefined; fiatSecp256k1CmovznzU32(&x535, x531, x520, x504); var x536: u32 = undefined; fiatSecp256k1CmovznzU32(&x536, x531, x522, x506); var x537: u32 = undefined; fiatSecp256k1CmovznzU32(&x537, x531, x524, x508); var x538: u32 = undefined; fiatSecp256k1CmovznzU32(&x538, x531, x526, x510); var x539: u32 = undefined; fiatSecp256k1CmovznzU32(&x539, x531, x528, x512); out1[0] = x532; out1[1] = x533; out1[2] = x534; out1[3] = x535; out1[4] = x536; out1[5] = x537; out1[6] = x538; out1[7] = x539; } /// The function fiatSecp256k1ToMontgomery translates a field element into the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1ToMontgomery(out1: *[8]u32, arg1: [8]u32) void { const x1: u32 = (arg1[1]); const x2: u32 = (arg1[2]); const x3: u32 = (arg1[3]); const x4: u32 = (arg1[4]); const x5: u32 = (arg1[5]); const x6: u32 = (arg1[6]); const x7: u32 = (arg1[7]); const x8: u32 = (arg1[0]); var x9: u32 = undefined; var x10: u32 = undefined; fiatSecp256k1MulxU32(&x9, &x10, x8, 0x7a2); var x11: u32 = undefined; var x12: u32 = undefined; fiatSecp256k1MulxU32(&x11, &x12, x8, 0xe90a1); var x13: u32 = undefined; var x14: u1 = undefined; fiatSecp256k1AddcarryxU32(&x13, &x14, 0x0, x12, x9); var x15: u32 = undefined; var x16: u1 = undefined; fiatSecp256k1AddcarryxU32(&x15, &x16, x14, x10, x8); var x17: u32 = undefined; var x18: u32 = undefined; fiatSecp256k1MulxU32(&x17, &x18, x11, 0xd2253531); var x19: u32 = undefined; var x20: u32 = undefined; fiatSecp256k1MulxU32(&x19, &x20, x17, 0xffffffff); var x21: u32 = undefined; var x22: u32 = undefined; fiatSecp256k1MulxU32(&x21, &x22, x17, 0xffffffff); var x23: u32 = undefined; var x24: u32 = undefined; fiatSecp256k1MulxU32(&x23, &x24, x17, 0xffffffff); var x25: u32 = undefined; var x26: u32 = undefined; fiatSecp256k1MulxU32(&x25, &x26, x17, 0xffffffff); var x27: u32 = undefined; var x28: u32 = undefined; fiatSecp256k1MulxU32(&x27, &x28, x17, 0xffffffff); var x29: u32 = undefined; var x30: u32 = undefined; fiatSecp256k1MulxU32(&x29, &x30, x17, 0xffffffff); var x31: u32 = undefined; var x32: u32 = undefined; fiatSecp256k1MulxU32(&x31, &x32, x17, 0xfffffffe); var x33: u32 = undefined; var x34: u32 = undefined; fiatSecp256k1MulxU32(&x33, &x34, x17, 0xfffffc2f); var x35: u32 = undefined; var x36: u1 = undefined; fiatSecp256k1AddcarryxU32(&x35, &x36, 0x0, x34, x31); var x37: u32 = undefined; var x38: u1 = undefined; fiatSecp256k1AddcarryxU32(&x37, &x38, x36, x32, x29); var x39: u32 = undefined; var x40: u1 = undefined; fiatSecp256k1AddcarryxU32(&x39, &x40, x38, x30, x27); var x41: u32 = undefined; var x42: u1 = undefined; fiatSecp256k1AddcarryxU32(&x41, &x42, x40, x28, x25); var x43: u32 = undefined; var x44: u1 = undefined; fiatSecp256k1AddcarryxU32(&x43, &x44, x42, x26, x23); var x45: u32 = undefined; var x46: u1 = undefined; fiatSecp256k1AddcarryxU32(&x45, &x46, x44, x24, x21); var x47: u32 = undefined; var x48: u1 = undefined; fiatSecp256k1AddcarryxU32(&x47, &x48, x46, x22, x19); var x49: u32 = undefined; var x50: u1 = undefined; fiatSecp256k1AddcarryxU32(&x49, &x50, 0x0, x11, x33); var x51: u32 = undefined; var x52: u1 = undefined; fiatSecp256k1AddcarryxU32(&x51, &x52, x50, x13, x35); var x53: u32 = undefined; var x54: u1 = undefined; fiatSecp256k1AddcarryxU32(&x53, &x54, x52, x15, x37); var x55: u32 = undefined; var x56: u1 = undefined; fiatSecp256k1AddcarryxU32(&x55, &x56, x54, @intCast(u32, x16), x39); var x57: u32 = undefined; var x58: u1 = undefined; fiatSecp256k1AddcarryxU32(&x57, &x58, x56, @intCast(u32, 0x0), x41); var x59: u32 = undefined; var x60: u1 = undefined; fiatSecp256k1AddcarryxU32(&x59, &x60, x58, @intCast(u32, 0x0), x43); var x61: u32 = undefined; var x62: u1 = undefined; fiatSecp256k1AddcarryxU32(&x61, &x62, x60, @intCast(u32, 0x0), x45); var x63: u32 = undefined; var x64: u1 = undefined; fiatSecp256k1AddcarryxU32(&x63, &x64, x62, @intCast(u32, 0x0), x47); var x65: u32 = undefined; var x66: u1 = undefined; fiatSecp256k1AddcarryxU32(&x65, &x66, x64, @intCast(u32, 0x0), (@intCast(u32, x48) + x20)); var x67: u32 = undefined; var x68: u32 = undefined; fiatSecp256k1MulxU32(&x67, &x68, x1, 0x7a2); var x69: u32 = undefined; var x70: u32 = undefined; fiatSecp256k1MulxU32(&x69, &x70, x1, 0xe90a1); var x71: u32 = undefined; var x72: u1 = undefined; fiatSecp256k1AddcarryxU32(&x71, &x72, 0x0, x70, x67); var x73: u32 = undefined; var x74: u1 = undefined; fiatSecp256k1AddcarryxU32(&x73, &x74, x72, x68, x1); var x75: u32 = undefined; var x76: u1 = undefined; fiatSecp256k1AddcarryxU32(&x75, &x76, 0x0, x51, x69); var x77: u32 = undefined; var x78: u1 = undefined; fiatSecp256k1AddcarryxU32(&x77, &x78, x76, x53, x71); var x79: u32 = undefined; var x80: u1 = undefined; fiatSecp256k1AddcarryxU32(&x79, &x80, x78, x55, x73); var x81: u32 = undefined; var x82: u1 = undefined; fiatSecp256k1AddcarryxU32(&x81, &x82, x80, x57, @intCast(u32, x74)); var x83: u32 = undefined; var x84: u1 = undefined; fiatSecp256k1AddcarryxU32(&x83, &x84, x82, x59, @intCast(u32, 0x0)); var x85: u32 = undefined; var x86: u1 = undefined; fiatSecp256k1AddcarryxU32(&x85, &x86, x84, x61, @intCast(u32, 0x0)); var x87: u32 = undefined; var x88: u1 = undefined; fiatSecp256k1AddcarryxU32(&x87, &x88, x86, x63, @intCast(u32, 0x0)); var x89: u32 = undefined; var x90: u1 = undefined; fiatSecp256k1AddcarryxU32(&x89, &x90, x88, x65, @intCast(u32, 0x0)); var x91: u32 = undefined; var x92: u32 = undefined; fiatSecp256k1MulxU32(&x91, &x92, x75, 0xd2253531); var x93: u32 = undefined; var x94: u32 = undefined; fiatSecp256k1MulxU32(&x93, &x94, x91, 0xffffffff); var x95: u32 = undefined; var x96: u32 = undefined; fiatSecp256k1MulxU32(&x95, &x96, x91, 0xffffffff); var x97: u32 = undefined; var x98: u32 = undefined; fiatSecp256k1MulxU32(&x97, &x98, x91, 0xffffffff); var x99: u32 = undefined; var x100: u32 = undefined; fiatSecp256k1MulxU32(&x99, &x100, x91, 0xffffffff); var x101: u32 = undefined; var x102: u32 = undefined; fiatSecp256k1MulxU32(&x101, &x102, x91, 0xffffffff); var x103: u32 = undefined; var x104: u32 = undefined; fiatSecp256k1MulxU32(&x103, &x104, x91, 0xffffffff); var x105: u32 = undefined; var x106: u32 = undefined; fiatSecp256k1MulxU32(&x105, &x106, x91, 0xfffffffe); var x107: u32 = undefined; var x108: u32 = undefined; fiatSecp256k1MulxU32(&x107, &x108, x91, 0xfffffc2f); var x109: u32 = undefined; var x110: u1 = undefined; fiatSecp256k1AddcarryxU32(&x109, &x110, 0x0, x108, x105); var x111: u32 = undefined; var x112: u1 = undefined; fiatSecp256k1AddcarryxU32(&x111, &x112, x110, x106, x103); var x113: u32 = undefined; var x114: u1 = undefined; fiatSecp256k1AddcarryxU32(&x113, &x114, x112, x104, x101); var x115: u32 = undefined; var x116: u1 = undefined; fiatSecp256k1AddcarryxU32(&x115, &x116, x114, x102, x99); var x117: u32 = undefined; var x118: u1 = undefined; fiatSecp256k1AddcarryxU32(&x117, &x118, x116, x100, x97); var x119: u32 = undefined; var x120: u1 = undefined; fiatSecp256k1AddcarryxU32(&x119, &x120, x118, x98, x95); var x121: u32 = undefined; var x122: u1 = undefined; fiatSecp256k1AddcarryxU32(&x121, &x122, x120, x96, x93); var x123: u32 = undefined; var x124: u1 = undefined; fiatSecp256k1AddcarryxU32(&x123, &x124, 0x0, x75, x107); var x125: u32 = undefined; var x126: u1 = undefined; fiatSecp256k1AddcarryxU32(&x125, &x126, x124, x77, x109); var x127: u32 = undefined; var x128: u1 = undefined; fiatSecp256k1AddcarryxU32(&x127, &x128, x126, x79, x111); var x129: u32 = undefined; var x130: u1 = undefined; fiatSecp256k1AddcarryxU32(&x129, &x130, x128, x81, x113); var x131: u32 = undefined; var x132: u1 = undefined; fiatSecp256k1AddcarryxU32(&x131, &x132, x130, x83, x115); var x133: u32 = undefined; var x134: u1 = undefined; fiatSecp256k1AddcarryxU32(&x133, &x134, x132, x85, x117); var x135: u32 = undefined; var x136: u1 = undefined; fiatSecp256k1AddcarryxU32(&x135, &x136, x134, x87, x119); var x137: u32 = undefined; var x138: u1 = undefined; fiatSecp256k1AddcarryxU32(&x137, &x138, x136, x89, x121); var x139: u32 = undefined; var x140: u1 = undefined; fiatSecp256k1AddcarryxU32(&x139, &x140, x138, (@intCast(u32, x90) + @intCast(u32, x66)), (@intCast(u32, x122) + x94)); var x141: u32 = undefined; var x142: u32 = undefined; fiatSecp256k1MulxU32(&x141, &x142, x2, 0x7a2); var x143: u32 = undefined; var x144: u32 = undefined; fiatSecp256k1MulxU32(&x143, &x144, x2, 0xe90a1); var x145: u32 = undefined; var x146: u1 = undefined; fiatSecp256k1AddcarryxU32(&x145, &x146, 0x0, x144, x141); var x147: u32 = undefined; var x148: u1 = undefined; fiatSecp256k1AddcarryxU32(&x147, &x148, x146, x142, x2); var x149: u32 = undefined; var x150: u1 = undefined; fiatSecp256k1AddcarryxU32(&x149, &x150, 0x0, x125, x143); var x151: u32 = undefined; var x152: u1 = undefined; fiatSecp256k1AddcarryxU32(&x151, &x152, x150, x127, x145); var x153: u32 = undefined; var x154: u1 = undefined; fiatSecp256k1AddcarryxU32(&x153, &x154, x152, x129, x147); var x155: u32 = undefined; var x156: u1 = undefined; fiatSecp256k1AddcarryxU32(&x155, &x156, x154, x131, @intCast(u32, x148)); var x157: u32 = undefined; var x158: u1 = undefined; fiatSecp256k1AddcarryxU32(&x157, &x158, x156, x133, @intCast(u32, 0x0)); var x159: u32 = undefined; var x160: u1 = undefined; fiatSecp256k1AddcarryxU32(&x159, &x160, x158, x135, @intCast(u32, 0x0)); var x161: u32 = undefined; var x162: u1 = undefined; fiatSecp256k1AddcarryxU32(&x161, &x162, x160, x137, @intCast(u32, 0x0)); var x163: u32 = undefined; var x164: u1 = undefined; fiatSecp256k1AddcarryxU32(&x163, &x164, x162, x139, @intCast(u32, 0x0)); var x165: u32 = undefined; var x166: u32 = undefined; fiatSecp256k1MulxU32(&x165, &x166, x149, 0xd2253531); var x167: u32 = undefined; var x168: u32 = undefined; fiatSecp256k1MulxU32(&x167, &x168, x165, 0xffffffff); var x169: u32 = undefined; var x170: u32 = undefined; fiatSecp256k1MulxU32(&x169, &x170, x165, 0xffffffff); var x171: u32 = undefined; var x172: u32 = undefined; fiatSecp256k1MulxU32(&x171, &x172, x165, 0xffffffff); var x173: u32 = undefined; var x174: u32 = undefined; fiatSecp256k1MulxU32(&x173, &x174, x165, 0xffffffff); var x175: u32 = undefined; var x176: u32 = undefined; fiatSecp256k1MulxU32(&x175, &x176, x165, 0xffffffff); var x177: u32 = undefined; var x178: u32 = undefined; fiatSecp256k1MulxU32(&x177, &x178, x165, 0xffffffff); var x179: u32 = undefined; var x180: u32 = undefined; fiatSecp256k1MulxU32(&x179, &x180, x165, 0xfffffffe); var x181: u32 = undefined; var x182: u32 = undefined; fiatSecp256k1MulxU32(&x181, &x182, x165, 0xfffffc2f); var x183: u32 = undefined; var x184: u1 = undefined; fiatSecp256k1AddcarryxU32(&x183, &x184, 0x0, x182, x179); var x185: u32 = undefined; var x186: u1 = undefined; fiatSecp256k1AddcarryxU32(&x185, &x186, x184, x180, x177); var x187: u32 = undefined; var x188: u1 = undefined; fiatSecp256k1AddcarryxU32(&x187, &x188, x186, x178, x175); var x189: u32 = undefined; var x190: u1 = undefined; fiatSecp256k1AddcarryxU32(&x189, &x190, x188, x176, x173); var x191: u32 = undefined; var x192: u1 = undefined; fiatSecp256k1AddcarryxU32(&x191, &x192, x190, x174, x171); var x193: u32 = undefined; var x194: u1 = undefined; fiatSecp256k1AddcarryxU32(&x193, &x194, x192, x172, x169); var x195: u32 = undefined; var x196: u1 = undefined; fiatSecp256k1AddcarryxU32(&x195, &x196, x194, x170, x167); var x197: u32 = undefined; var x198: u1 = undefined; fiatSecp256k1AddcarryxU32(&x197, &x198, 0x0, x149, x181); var x199: u32 = undefined; var x200: u1 = undefined; fiatSecp256k1AddcarryxU32(&x199, &x200, x198, x151, x183); var x201: u32 = undefined; var x202: u1 = undefined; fiatSecp256k1AddcarryxU32(&x201, &x202, x200, x153, x185); var x203: u32 = undefined; var x204: u1 = undefined; fiatSecp256k1AddcarryxU32(&x203, &x204, x202, x155, x187); var x205: u32 = undefined; var x206: u1 = undefined; fiatSecp256k1AddcarryxU32(&x205, &x206, x204, x157, x189); var x207: u32 = undefined; var x208: u1 = undefined; fiatSecp256k1AddcarryxU32(&x207, &x208, x206, x159, x191); var x209: u32 = undefined; var x210: u1 = undefined; fiatSecp256k1AddcarryxU32(&x209, &x210, x208, x161, x193); var x211: u32 = undefined; var x212: u1 = undefined; fiatSecp256k1AddcarryxU32(&x211, &x212, x210, x163, x195); var x213: u32 = undefined; var x214: u1 = undefined; fiatSecp256k1AddcarryxU32(&x213, &x214, x212, (@intCast(u32, x164) + @intCast(u32, x140)), (@intCast(u32, x196) + x168)); var x215: u32 = undefined; var x216: u32 = undefined; fiatSecp256k1MulxU32(&x215, &x216, x3, 0x7a2); var x217: u32 = undefined; var x218: u32 = undefined; fiatSecp256k1MulxU32(&x217, &x218, x3, 0xe90a1); var x219: u32 = undefined; var x220: u1 = undefined; fiatSecp256k1AddcarryxU32(&x219, &x220, 0x0, x218, x215); var x221: u32 = undefined; var x222: u1 = undefined; fiatSecp256k1AddcarryxU32(&x221, &x222, x220, x216, x3); var x223: u32 = undefined; var x224: u1 = undefined; fiatSecp256k1AddcarryxU32(&x223, &x224, 0x0, x199, x217); var x225: u32 = undefined; var x226: u1 = undefined; fiatSecp256k1AddcarryxU32(&x225, &x226, x224, x201, x219); var x227: u32 = undefined; var x228: u1 = undefined; fiatSecp256k1AddcarryxU32(&x227, &x228, x226, x203, x221); var x229: u32 = undefined; var x230: u1 = undefined; fiatSecp256k1AddcarryxU32(&x229, &x230, x228, x205, @intCast(u32, x222)); var x231: u32 = undefined; var x232: u1 = undefined; fiatSecp256k1AddcarryxU32(&x231, &x232, x230, x207, @intCast(u32, 0x0)); var x233: u32 = undefined; var x234: u1 = undefined; fiatSecp256k1AddcarryxU32(&x233, &x234, x232, x209, @intCast(u32, 0x0)); var x235: u32 = undefined; var x236: u1 = undefined; fiatSecp256k1AddcarryxU32(&x235, &x236, x234, x211, @intCast(u32, 0x0)); var x237: u32 = undefined; var x238: u1 = undefined; fiatSecp256k1AddcarryxU32(&x237, &x238, x236, x213, @intCast(u32, 0x0)); var x239: u32 = undefined; var x240: u32 = undefined; fiatSecp256k1MulxU32(&x239, &x240, x223, 0xd2253531); var x241: u32 = undefined; var x242: u32 = undefined; fiatSecp256k1MulxU32(&x241, &x242, x239, 0xffffffff); var x243: u32 = undefined; var x244: u32 = undefined; fiatSecp256k1MulxU32(&x243, &x244, x239, 0xffffffff); var x245: u32 = undefined; var x246: u32 = undefined; fiatSecp256k1MulxU32(&x245, &x246, x239, 0xffffffff); var x247: u32 = undefined; var x248: u32 = undefined; fiatSecp256k1MulxU32(&x247, &x248, x239, 0xffffffff); var x249: u32 = undefined; var x250: u32 = undefined; fiatSecp256k1MulxU32(&x249, &x250, x239, 0xffffffff); var x251: u32 = undefined; var x252: u32 = undefined; fiatSecp256k1MulxU32(&x251, &x252, x239, 0xffffffff); var x253: u32 = undefined; var x254: u32 = undefined; fiatSecp256k1MulxU32(&x253, &x254, x239, 0xfffffffe); var x255: u32 = undefined; var x256: u32 = undefined; fiatSecp256k1MulxU32(&x255, &x256, x239, 0xfffffc2f); var x257: u32 = undefined; var x258: u1 = undefined; fiatSecp256k1AddcarryxU32(&x257, &x258, 0x0, x256, x253); var x259: u32 = undefined; var x260: u1 = undefined; fiatSecp256k1AddcarryxU32(&x259, &x260, x258, x254, x251); var x261: u32 = undefined; var x262: u1 = undefined; fiatSecp256k1AddcarryxU32(&x261, &x262, x260, x252, x249); var x263: u32 = undefined; var x264: u1 = undefined; fiatSecp256k1AddcarryxU32(&x263, &x264, x262, x250, x247); var x265: u32 = undefined; var x266: u1 = undefined; fiatSecp256k1AddcarryxU32(&x265, &x266, x264, x248, x245); var x267: u32 = undefined; var x268: u1 = undefined; fiatSecp256k1AddcarryxU32(&x267, &x268, x266, x246, x243); var x269: u32 = undefined; var x270: u1 = undefined; fiatSecp256k1AddcarryxU32(&x269, &x270, x268, x244, x241); var x271: u32 = undefined; var x272: u1 = undefined; fiatSecp256k1AddcarryxU32(&x271, &x272, 0x0, x223, x255); var x273: u32 = undefined; var x274: u1 = undefined; fiatSecp256k1AddcarryxU32(&x273, &x274, x272, x225, x257); var x275: u32 = undefined; var x276: u1 = undefined; fiatSecp256k1AddcarryxU32(&x275, &x276, x274, x227, x259); var x277: u32 = undefined; var x278: u1 = undefined; fiatSecp256k1AddcarryxU32(&x277, &x278, x276, x229, x261); var x279: u32 = undefined; var x280: u1 = undefined; fiatSecp256k1AddcarryxU32(&x279, &x280, x278, x231, x263); var x281: u32 = undefined; var x282: u1 = undefined; fiatSecp256k1AddcarryxU32(&x281, &x282, x280, x233, x265); var x283: u32 = undefined; var x284: u1 = undefined; fiatSecp256k1AddcarryxU32(&x283, &x284, x282, x235, x267); var x285: u32 = undefined; var x286: u1 = undefined; fiatSecp256k1AddcarryxU32(&x285, &x286, x284, x237, x269); var x287: u32 = undefined; var x288: u1 = undefined; fiatSecp256k1AddcarryxU32(&x287, &x288, x286, (@intCast(u32, x238) + @intCast(u32, x214)), (@intCast(u32, x270) + x242)); var x289: u32 = undefined; var x290: u32 = undefined; fiatSecp256k1MulxU32(&x289, &x290, x4, 0x7a2); var x291: u32 = undefined; var x292: u32 = undefined; fiatSecp256k1MulxU32(&x291, &x292, x4, 0xe90a1); var x293: u32 = undefined; var x294: u1 = undefined; fiatSecp256k1AddcarryxU32(&x293, &x294, 0x0, x292, x289); var x295: u32 = undefined; var x296: u1 = undefined; fiatSecp256k1AddcarryxU32(&x295, &x296, x294, x290, x4); var x297: u32 = undefined; var x298: u1 = undefined; fiatSecp256k1AddcarryxU32(&x297, &x298, 0x0, x273, x291); var x299: u32 = undefined; var x300: u1 = undefined; fiatSecp256k1AddcarryxU32(&x299, &x300, x298, x275, x293); var x301: u32 = undefined; var x302: u1 = undefined; fiatSecp256k1AddcarryxU32(&x301, &x302, x300, x277, x295); var x303: u32 = undefined; var x304: u1 = undefined; fiatSecp256k1AddcarryxU32(&x303, &x304, x302, x279, @intCast(u32, x296)); var x305: u32 = undefined; var x306: u1 = undefined; fiatSecp256k1AddcarryxU32(&x305, &x306, x304, x281, @intCast(u32, 0x0)); var x307: u32 = undefined; var x308: u1 = undefined; fiatSecp256k1AddcarryxU32(&x307, &x308, x306, x283, @intCast(u32, 0x0)); var x309: u32 = undefined; var x310: u1 = undefined; fiatSecp256k1AddcarryxU32(&x309, &x310, x308, x285, @intCast(u32, 0x0)); var x311: u32 = undefined; var x312: u1 = undefined; fiatSecp256k1AddcarryxU32(&x311, &x312, x310, x287, @intCast(u32, 0x0)); var x313: u32 = undefined; var x314: u32 = undefined; fiatSecp256k1MulxU32(&x313, &x314, x297, 0xd2253531); var x315: u32 = undefined; var x316: u32 = undefined; fiatSecp256k1MulxU32(&x315, &x316, x313, 0xffffffff); var x317: u32 = undefined; var x318: u32 = undefined; fiatSecp256k1MulxU32(&x317, &x318, x313, 0xffffffff); var x319: u32 = undefined; var x320: u32 = undefined; fiatSecp256k1MulxU32(&x319, &x320, x313, 0xffffffff); var x321: u32 = undefined; var x322: u32 = undefined; fiatSecp256k1MulxU32(&x321, &x322, x313, 0xffffffff); var x323: u32 = undefined; var x324: u32 = undefined; fiatSecp256k1MulxU32(&x323, &x324, x313, 0xffffffff); var x325: u32 = undefined; var x326: u32 = undefined; fiatSecp256k1MulxU32(&x325, &x326, x313, 0xffffffff); var x327: u32 = undefined; var x328: u32 = undefined; fiatSecp256k1MulxU32(&x327, &x328, x313, 0xfffffffe); var x329: u32 = undefined; var x330: u32 = undefined; fiatSecp256k1MulxU32(&x329, &x330, x313, 0xfffffc2f); var x331: u32 = undefined; var x332: u1 = undefined; fiatSecp256k1AddcarryxU32(&x331, &x332, 0x0, x330, x327); var x333: u32 = undefined; var x334: u1 = undefined; fiatSecp256k1AddcarryxU32(&x333, &x334, x332, x328, x325); var x335: u32 = undefined; var x336: u1 = undefined; fiatSecp256k1AddcarryxU32(&x335, &x336, x334, x326, x323); var x337: u32 = undefined; var x338: u1 = undefined; fiatSecp256k1AddcarryxU32(&x337, &x338, x336, x324, x321); var x339: u32 = undefined; var x340: u1 = undefined; fiatSecp256k1AddcarryxU32(&x339, &x340, x338, x322, x319); var x341: u32 = undefined; var x342: u1 = undefined; fiatSecp256k1AddcarryxU32(&x341, &x342, x340, x320, x317); var x343: u32 = undefined; var x344: u1 = undefined; fiatSecp256k1AddcarryxU32(&x343, &x344, x342, x318, x315); var x345: u32 = undefined; var x346: u1 = undefined; fiatSecp256k1AddcarryxU32(&x345, &x346, 0x0, x297, x329); var x347: u32 = undefined; var x348: u1 = undefined; fiatSecp256k1AddcarryxU32(&x347, &x348, x346, x299, x331); var x349: u32 = undefined; var x350: u1 = undefined; fiatSecp256k1AddcarryxU32(&x349, &x350, x348, x301, x333); var x351: u32 = undefined; var x352: u1 = undefined; fiatSecp256k1AddcarryxU32(&x351, &x352, x350, x303, x335); var x353: u32 = undefined; var x354: u1 = undefined; fiatSecp256k1AddcarryxU32(&x353, &x354, x352, x305, x337); var x355: u32 = undefined; var x356: u1 = undefined; fiatSecp256k1AddcarryxU32(&x355, &x356, x354, x307, x339); var x357: u32 = undefined; var x358: u1 = undefined; fiatSecp256k1AddcarryxU32(&x357, &x358, x356, x309, x341); var x359: u32 = undefined; var x360: u1 = undefined; fiatSecp256k1AddcarryxU32(&x359, &x360, x358, x311, x343); var x361: u32 = undefined; var x362: u1 = undefined; fiatSecp256k1AddcarryxU32(&x361, &x362, x360, (@intCast(u32, x312) + @intCast(u32, x288)), (@intCast(u32, x344) + x316)); var x363: u32 = undefined; var x364: u32 = undefined; fiatSecp256k1MulxU32(&x363, &x364, x5, 0x7a2); var x365: u32 = undefined; var x366: u32 = undefined; fiatSecp256k1MulxU32(&x365, &x366, x5, 0xe90a1); var x367: u32 = undefined; var x368: u1 = undefined; fiatSecp256k1AddcarryxU32(&x367, &x368, 0x0, x366, x363); var x369: u32 = undefined; var x370: u1 = undefined; fiatSecp256k1AddcarryxU32(&x369, &x370, x368, x364, x5); var x371: u32 = undefined; var x372: u1 = undefined; fiatSecp256k1AddcarryxU32(&x371, &x372, 0x0, x347, x365); var x373: u32 = undefined; var x374: u1 = undefined; fiatSecp256k1AddcarryxU32(&x373, &x374, x372, x349, x367); var x375: u32 = undefined; var x376: u1 = undefined; fiatSecp256k1AddcarryxU32(&x375, &x376, x374, x351, x369); var x377: u32 = undefined; var x378: u1 = undefined; fiatSecp256k1AddcarryxU32(&x377, &x378, x376, x353, @intCast(u32, x370)); var x379: u32 = undefined; var x380: u1 = undefined; fiatSecp256k1AddcarryxU32(&x379, &x380, x378, x355, @intCast(u32, 0x0)); var x381: u32 = undefined; var x382: u1 = undefined; fiatSecp256k1AddcarryxU32(&x381, &x382, x380, x357, @intCast(u32, 0x0)); var x383: u32 = undefined; var x384: u1 = undefined; fiatSecp256k1AddcarryxU32(&x383, &x384, x382, x359, @intCast(u32, 0x0)); var x385: u32 = undefined; var x386: u1 = undefined; fiatSecp256k1AddcarryxU32(&x385, &x386, x384, x361, @intCast(u32, 0x0)); var x387: u32 = undefined; var x388: u32 = undefined; fiatSecp256k1MulxU32(&x387, &x388, x371, 0xd2253531); var x389: u32 = undefined; var x390: u32 = undefined; fiatSecp256k1MulxU32(&x389, &x390, x387, 0xffffffff); var x391: u32 = undefined; var x392: u32 = undefined; fiatSecp256k1MulxU32(&x391, &x392, x387, 0xffffffff); var x393: u32 = undefined; var x394: u32 = undefined; fiatSecp256k1MulxU32(&x393, &x394, x387, 0xffffffff); var x395: u32 = undefined; var x396: u32 = undefined; fiatSecp256k1MulxU32(&x395, &x396, x387, 0xffffffff); var x397: u32 = undefined; var x398: u32 = undefined; fiatSecp256k1MulxU32(&x397, &x398, x387, 0xffffffff); var x399: u32 = undefined; var x400: u32 = undefined; fiatSecp256k1MulxU32(&x399, &x400, x387, 0xffffffff); var x401: u32 = undefined; var x402: u32 = undefined; fiatSecp256k1MulxU32(&x401, &x402, x387, 0xfffffffe); var x403: u32 = undefined; var x404: u32 = undefined; fiatSecp256k1MulxU32(&x403, &x404, x387, 0xfffffc2f); var x405: u32 = undefined; var x406: u1 = undefined; fiatSecp256k1AddcarryxU32(&x405, &x406, 0x0, x404, x401); var x407: u32 = undefined; var x408: u1 = undefined; fiatSecp256k1AddcarryxU32(&x407, &x408, x406, x402, x399); var x409: u32 = undefined; var x410: u1 = undefined; fiatSecp256k1AddcarryxU32(&x409, &x410, x408, x400, x397); var x411: u32 = undefined; var x412: u1 = undefined; fiatSecp256k1AddcarryxU32(&x411, &x412, x410, x398, x395); var x413: u32 = undefined; var x414: u1 = undefined; fiatSecp256k1AddcarryxU32(&x413, &x414, x412, x396, x393); var x415: u32 = undefined; var x416: u1 = undefined; fiatSecp256k1AddcarryxU32(&x415, &x416, x414, x394, x391); var x417: u32 = undefined; var x418: u1 = undefined; fiatSecp256k1AddcarryxU32(&x417, &x418, x416, x392, x389); var x419: u32 = undefined; var x420: u1 = undefined; fiatSecp256k1AddcarryxU32(&x419, &x420, 0x0, x371, x403); var x421: u32 = undefined; var x422: u1 = undefined; fiatSecp256k1AddcarryxU32(&x421, &x422, x420, x373, x405); var x423: u32 = undefined; var x424: u1 = undefined; fiatSecp256k1AddcarryxU32(&x423, &x424, x422, x375, x407); var x425: u32 = undefined; var x426: u1 = undefined; fiatSecp256k1AddcarryxU32(&x425, &x426, x424, x377, x409); var x427: u32 = undefined; var x428: u1 = undefined; fiatSecp256k1AddcarryxU32(&x427, &x428, x426, x379, x411); var x429: u32 = undefined; var x430: u1 = undefined; fiatSecp256k1AddcarryxU32(&x429, &x430, x428, x381, x413); var x431: u32 = undefined; var x432: u1 = undefined; fiatSecp256k1AddcarryxU32(&x431, &x432, x430, x383, x415); var x433: u32 = undefined; var x434: u1 = undefined; fiatSecp256k1AddcarryxU32(&x433, &x434, x432, x385, x417); var x435: u32 = undefined; var x436: u1 = undefined; fiatSecp256k1AddcarryxU32(&x435, &x436, x434, (@intCast(u32, x386) + @intCast(u32, x362)), (@intCast(u32, x418) + x390)); var x437: u32 = undefined; var x438: u32 = undefined; fiatSecp256k1MulxU32(&x437, &x438, x6, 0x7a2); var x439: u32 = undefined; var x440: u32 = undefined; fiatSecp256k1MulxU32(&x439, &x440, x6, 0xe90a1); var x441: u32 = undefined; var x442: u1 = undefined; fiatSecp256k1AddcarryxU32(&x441, &x442, 0x0, x440, x437); var x443: u32 = undefined; var x444: u1 = undefined; fiatSecp256k1AddcarryxU32(&x443, &x444, x442, x438, x6); var x445: u32 = undefined; var x446: u1 = undefined; fiatSecp256k1AddcarryxU32(&x445, &x446, 0x0, x421, x439); var x447: u32 = undefined; var x448: u1 = undefined; fiatSecp256k1AddcarryxU32(&x447, &x448, x446, x423, x441); var x449: u32 = undefined; var x450: u1 = undefined; fiatSecp256k1AddcarryxU32(&x449, &x450, x448, x425, x443); var x451: u32 = undefined; var x452: u1 = undefined; fiatSecp256k1AddcarryxU32(&x451, &x452, x450, x427, @intCast(u32, x444)); var x453: u32 = undefined; var x454: u1 = undefined; fiatSecp256k1AddcarryxU32(&x453, &x454, x452, x429, @intCast(u32, 0x0)); var x455: u32 = undefined; var x456: u1 = undefined; fiatSecp256k1AddcarryxU32(&x455, &x456, x454, x431, @intCast(u32, 0x0)); var x457: u32 = undefined; var x458: u1 = undefined; fiatSecp256k1AddcarryxU32(&x457, &x458, x456, x433, @intCast(u32, 0x0)); var x459: u32 = undefined; var x460: u1 = undefined; fiatSecp256k1AddcarryxU32(&x459, &x460, x458, x435, @intCast(u32, 0x0)); var x461: u32 = undefined; var x462: u32 = undefined; fiatSecp256k1MulxU32(&x461, &x462, x445, 0xd2253531); var x463: u32 = undefined; var x464: u32 = undefined; fiatSecp256k1MulxU32(&x463, &x464, x461, 0xffffffff); var x465: u32 = undefined; var x466: u32 = undefined; fiatSecp256k1MulxU32(&x465, &x466, x461, 0xffffffff); var x467: u32 = undefined; var x468: u32 = undefined; fiatSecp256k1MulxU32(&x467, &x468, x461, 0xffffffff); var x469: u32 = undefined; var x470: u32 = undefined; fiatSecp256k1MulxU32(&x469, &x470, x461, 0xffffffff); var x471: u32 = undefined; var x472: u32 = undefined; fiatSecp256k1MulxU32(&x471, &x472, x461, 0xffffffff); var x473: u32 = undefined; var x474: u32 = undefined; fiatSecp256k1MulxU32(&x473, &x474, x461, 0xffffffff); var x475: u32 = undefined; var x476: u32 = undefined; fiatSecp256k1MulxU32(&x475, &x476, x461, 0xfffffffe); var x477: u32 = undefined; var x478: u32 = undefined; fiatSecp256k1MulxU32(&x477, &x478, x461, 0xfffffc2f); var x479: u32 = undefined; var x480: u1 = undefined; fiatSecp256k1AddcarryxU32(&x479, &x480, 0x0, x478, x475); var x481: u32 = undefined; var x482: u1 = undefined; fiatSecp256k1AddcarryxU32(&x481, &x482, x480, x476, x473); var x483: u32 = undefined; var x484: u1 = undefined; fiatSecp256k1AddcarryxU32(&x483, &x484, x482, x474, x471); var x485: u32 = undefined; var x486: u1 = undefined; fiatSecp256k1AddcarryxU32(&x485, &x486, x484, x472, x469); var x487: u32 = undefined; var x488: u1 = undefined; fiatSecp256k1AddcarryxU32(&x487, &x488, x486, x470, x467); var x489: u32 = undefined; var x490: u1 = undefined; fiatSecp256k1AddcarryxU32(&x489, &x490, x488, x468, x465); var x491: u32 = undefined; var x492: u1 = undefined; fiatSecp256k1AddcarryxU32(&x491, &x492, x490, x466, x463); var x493: u32 = undefined; var x494: u1 = undefined; fiatSecp256k1AddcarryxU32(&x493, &x494, 0x0, x445, x477); var x495: u32 = undefined; var x496: u1 = undefined; fiatSecp256k1AddcarryxU32(&x495, &x496, x494, x447, x479); var x497: u32 = undefined; var x498: u1 = undefined; fiatSecp256k1AddcarryxU32(&x497, &x498, x496, x449, x481); var x499: u32 = undefined; var x500: u1 = undefined; fiatSecp256k1AddcarryxU32(&x499, &x500, x498, x451, x483); var x501: u32 = undefined; var x502: u1 = undefined; fiatSecp256k1AddcarryxU32(&x501, &x502, x500, x453, x485); var x503: u32 = undefined; var x504: u1 = undefined; fiatSecp256k1AddcarryxU32(&x503, &x504, x502, x455, x487); var x505: u32 = undefined; var x506: u1 = undefined; fiatSecp256k1AddcarryxU32(&x505, &x506, x504, x457, x489); var x507: u32 = undefined; var x508: u1 = undefined; fiatSecp256k1AddcarryxU32(&x507, &x508, x506, x459, x491); var x509: u32 = undefined; var x510: u1 = undefined; fiatSecp256k1AddcarryxU32(&x509, &x510, x508, (@intCast(u32, x460) + @intCast(u32, x436)), (@intCast(u32, x492) + x464)); var x511: u32 = undefined; var x512: u32 = undefined; fiatSecp256k1MulxU32(&x511, &x512, x7, 0x7a2); var x513: u32 = undefined; var x514: u32 = undefined; fiatSecp256k1MulxU32(&x513, &x514, x7, 0xe90a1); var x515: u32 = undefined; var x516: u1 = undefined; fiatSecp256k1AddcarryxU32(&x515, &x516, 0x0, x514, x511); var x517: u32 = undefined; var x518: u1 = undefined; fiatSecp256k1AddcarryxU32(&x517, &x518, x516, x512, x7); var x519: u32 = undefined; var x520: u1 = undefined; fiatSecp256k1AddcarryxU32(&x519, &x520, 0x0, x495, x513); var x521: u32 = undefined; var x522: u1 = undefined; fiatSecp256k1AddcarryxU32(&x521, &x522, x520, x497, x515); var x523: u32 = undefined; var x524: u1 = undefined; fiatSecp256k1AddcarryxU32(&x523, &x524, x522, x499, x517); var x525: u32 = undefined; var x526: u1 = undefined; fiatSecp256k1AddcarryxU32(&x525, &x526, x524, x501, @intCast(u32, x518)); var x527: u32 = undefined; var x528: u1 = undefined; fiatSecp256k1AddcarryxU32(&x527, &x528, x526, x503, @intCast(u32, 0x0)); var x529: u32 = undefined; var x530: u1 = undefined; fiatSecp256k1AddcarryxU32(&x529, &x530, x528, x505, @intCast(u32, 0x0)); var x531: u32 = undefined; var x532: u1 = undefined; fiatSecp256k1AddcarryxU32(&x531, &x532, x530, x507, @intCast(u32, 0x0)); var x533: u32 = undefined; var x534: u1 = undefined; fiatSecp256k1AddcarryxU32(&x533, &x534, x532, x509, @intCast(u32, 0x0)); var x535: u32 = undefined; var x536: u32 = undefined; fiatSecp256k1MulxU32(&x535, &x536, x519, 0xd2253531); var x537: u32 = undefined; var x538: u32 = undefined; fiatSecp256k1MulxU32(&x537, &x538, x535, 0xffffffff); var x539: u32 = undefined; var x540: u32 = undefined; fiatSecp256k1MulxU32(&x539, &x540, x535, 0xffffffff); var x541: u32 = undefined; var x542: u32 = undefined; fiatSecp256k1MulxU32(&x541, &x542, x535, 0xffffffff); var x543: u32 = undefined; var x544: u32 = undefined; fiatSecp256k1MulxU32(&x543, &x544, x535, 0xffffffff); var x545: u32 = undefined; var x546: u32 = undefined; fiatSecp256k1MulxU32(&x545, &x546, x535, 0xffffffff); var x547: u32 = undefined; var x548: u32 = undefined; fiatSecp256k1MulxU32(&x547, &x548, x535, 0xffffffff); var x549: u32 = undefined; var x550: u32 = undefined; fiatSecp256k1MulxU32(&x549, &x550, x535, 0xfffffffe); var x551: u32 = undefined; var x552: u32 = undefined; fiatSecp256k1MulxU32(&x551, &x552, x535, 0xfffffc2f); var x553: u32 = undefined; var x554: u1 = undefined; fiatSecp256k1AddcarryxU32(&x553, &x554, 0x0, x552, x549); var x555: u32 = undefined; var x556: u1 = undefined; fiatSecp256k1AddcarryxU32(&x555, &x556, x554, x550, x547); var x557: u32 = undefined; var x558: u1 = undefined; fiatSecp256k1AddcarryxU32(&x557, &x558, x556, x548, x545); var x559: u32 = undefined; var x560: u1 = undefined; fiatSecp256k1AddcarryxU32(&x559, &x560, x558, x546, x543); var x561: u32 = undefined; var x562: u1 = undefined; fiatSecp256k1AddcarryxU32(&x561, &x562, x560, x544, x541); var x563: u32 = undefined; var x564: u1 = undefined; fiatSecp256k1AddcarryxU32(&x563, &x564, x562, x542, x539); var x565: u32 = undefined; var x566: u1 = undefined; fiatSecp256k1AddcarryxU32(&x565, &x566, x564, x540, x537); var x567: u32 = undefined; var x568: u1 = undefined; fiatSecp256k1AddcarryxU32(&x567, &x568, 0x0, x519, x551); var x569: u32 = undefined; var x570: u1 = undefined; fiatSecp256k1AddcarryxU32(&x569, &x570, x568, x521, x553); var x571: u32 = undefined; var x572: u1 = undefined; fiatSecp256k1AddcarryxU32(&x571, &x572, x570, x523, x555); var x573: u32 = undefined; var x574: u1 = undefined; fiatSecp256k1AddcarryxU32(&x573, &x574, x572, x525, x557); var x575: u32 = undefined; var x576: u1 = undefined; fiatSecp256k1AddcarryxU32(&x575, &x576, x574, x527, x559); var x577: u32 = undefined; var x578: u1 = undefined; fiatSecp256k1AddcarryxU32(&x577, &x578, x576, x529, x561); var x579: u32 = undefined; var x580: u1 = undefined; fiatSecp256k1AddcarryxU32(&x579, &x580, x578, x531, x563); var x581: u32 = undefined; var x582: u1 = undefined; fiatSecp256k1AddcarryxU32(&x581, &x582, x580, x533, x565); var x583: u32 = undefined; var x584: u1 = undefined; fiatSecp256k1AddcarryxU32(&x583, &x584, x582, (@intCast(u32, x534) + @intCast(u32, x510)), (@intCast(u32, x566) + x538)); var x585: u32 = undefined; var x586: u1 = undefined; fiatSecp256k1SubborrowxU32(&x585, &x586, 0x0, x569, 0xfffffc2f); var x587: u32 = undefined; var x588: u1 = undefined; fiatSecp256k1SubborrowxU32(&x587, &x588, x586, x571, 0xfffffffe); var x589: u32 = undefined; var x590: u1 = undefined; fiatSecp256k1SubborrowxU32(&x589, &x590, x588, x573, 0xffffffff); var x591: u32 = undefined; var x592: u1 = undefined; fiatSecp256k1SubborrowxU32(&x591, &x592, x590, x575, 0xffffffff); var x593: u32 = undefined; var x594: u1 = undefined; fiatSecp256k1SubborrowxU32(&x593, &x594, x592, x577, 0xffffffff); var x595: u32 = undefined; var x596: u1 = undefined; fiatSecp256k1SubborrowxU32(&x595, &x596, x594, x579, 0xffffffff); var x597: u32 = undefined; var x598: u1 = undefined; fiatSecp256k1SubborrowxU32(&x597, &x598, x596, x581, 0xffffffff); var x599: u32 = undefined; var x600: u1 = undefined; fiatSecp256k1SubborrowxU32(&x599, &x600, x598, x583, 0xffffffff); var x601: u32 = undefined; var x602: u1 = undefined; fiatSecp256k1SubborrowxU32(&x601, &x602, x600, @intCast(u32, x584), @intCast(u32, 0x0)); var x603: u32 = undefined; fiatSecp256k1CmovznzU32(&x603, x602, x585, x569); var x604: u32 = undefined; fiatSecp256k1CmovznzU32(&x604, x602, x587, x571); var x605: u32 = undefined; fiatSecp256k1CmovznzU32(&x605, x602, x589, x573); var x606: u32 = undefined; fiatSecp256k1CmovznzU32(&x606, x602, x591, x575); var x607: u32 = undefined; fiatSecp256k1CmovznzU32(&x607, x602, x593, x577); var x608: u32 = undefined; fiatSecp256k1CmovznzU32(&x608, x602, x595, x579); var x609: u32 = undefined; fiatSecp256k1CmovznzU32(&x609, x602, x597, x581); var x610: u32 = undefined; fiatSecp256k1CmovznzU32(&x610, x602, x599, x583); out1[0] = x603; out1[1] = x604; out1[2] = x605; out1[3] = x606; out1[4] = x607; out1[5] = x608; out1[6] = x609; out1[7] = x610; } /// The function fiatSecp256k1Nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] pub fn fiatSecp256k1Nonzero(out1: *u32, arg1: [8]u32) void { const x1: u32 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | ((arg1[6]) | (arg1[7])))))))); out1.* = x1; } /// The function fiatSecp256k1Selectznz is a multi-limb conditional select. /// Postconditions: /// eval out1 = (if arg1 = 0 then eval arg2 else eval arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Selectznz(out1: *[8]u32, arg1: u1, arg2: [8]u32, arg3: [8]u32) void { var x1: u32 = undefined; fiatSecp256k1CmovznzU32(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u32 = undefined; fiatSecp256k1CmovznzU32(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u32 = undefined; fiatSecp256k1CmovznzU32(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u32 = undefined; fiatSecp256k1CmovznzU32(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u32 = undefined; fiatSecp256k1CmovznzU32(&x5, arg1, (arg2[4]), (arg3[4])); var x6: u32 = undefined; fiatSecp256k1CmovznzU32(&x6, arg1, (arg2[5]), (arg3[5])); var x7: u32 = undefined; fiatSecp256k1CmovznzU32(&x7, arg1, (arg2[6]), (arg3[6])); var x8: u32 = undefined; fiatSecp256k1CmovznzU32(&x8, arg1, (arg2[7]), (arg3[7])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; } /// The function fiatSecp256k1ToBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] pub fn fiatSecp256k1ToBytes(out1: *[32]u8, arg1: [8]u32) void { const x1: u32 = (arg1[7]); const x2: u32 = (arg1[6]); const x3: u32 = (arg1[5]); const x4: u32 = (arg1[4]); const x5: u32 = (arg1[3]); const x6: u32 = (arg1[2]); const x7: u32 = (arg1[1]); const x8: u32 = (arg1[0]); const x9: u8 = @intCast(u8, (x8 & @intCast(u32, 0xff))); const x10: u32 = (x8 >> 8); const x11: u8 = @intCast(u8, (x10 & @intCast(u32, 0xff))); const x12: u32 = (x10 >> 8); const x13: u8 = @intCast(u8, (x12 & @intCast(u32, 0xff))); const x14: u8 = @intCast(u8, (x12 >> 8)); const x15: u8 = @intCast(u8, (x7 & @intCast(u32, 0xff))); const x16: u32 = (x7 >> 8); const x17: u8 = @intCast(u8, (x16 & @intCast(u32, 0xff))); const x18: u32 = (x16 >> 8); const x19: u8 = @intCast(u8, (x18 & @intCast(u32, 0xff))); const x20: u8 = @intCast(u8, (x18 >> 8)); const x21: u8 = @intCast(u8, (x6 & @intCast(u32, 0xff))); const x22: u32 = (x6 >> 8); const x23: u8 = @intCast(u8, (x22 & @intCast(u32, 0xff))); const x24: u32 = (x22 >> 8); const x25: u8 = @intCast(u8, (x24 & @intCast(u32, 0xff))); const x26: u8 = @intCast(u8, (x24 >> 8)); const x27: u8 = @intCast(u8, (x5 & @intCast(u32, 0xff))); const x28: u32 = (x5 >> 8); const x29: u8 = @intCast(u8, (x28 & @intCast(u32, 0xff))); const x30: u32 = (x28 >> 8); const x31: u8 = @intCast(u8, (x30 & @intCast(u32, 0xff))); const x32: u8 = @intCast(u8, (x30 >> 8)); const x33: u8 = @intCast(u8, (x4 & @intCast(u32, 0xff))); const x34: u32 = (x4 >> 8); const x35: u8 = @intCast(u8, (x34 & @intCast(u32, 0xff))); const x36: u32 = (x34 >> 8); const x37: u8 = @intCast(u8, (x36 & @intCast(u32, 0xff))); const x38: u8 = @intCast(u8, (x36 >> 8)); const x39: u8 = @intCast(u8, (x3 & @intCast(u32, 0xff))); const x40: u32 = (x3 >> 8); const x41: u8 = @intCast(u8, (x40 & @intCast(u32, 0xff))); const x42: u32 = (x40 >> 8); const x43: u8 = @intCast(u8, (x42 & @intCast(u32, 0xff))); const x44: u8 = @intCast(u8, (x42 >> 8)); const x45: u8 = @intCast(u8, (x2 & @intCast(u32, 0xff))); const x46: u32 = (x2 >> 8); const x47: u8 = @intCast(u8, (x46 & @intCast(u32, 0xff))); const x48: u32 = (x46 >> 8); const x49: u8 = @intCast(u8, (x48 & @intCast(u32, 0xff))); const x50: u8 = @intCast(u8, (x48 >> 8)); const x51: u8 = @intCast(u8, (x1 & @intCast(u32, 0xff))); const x52: u32 = (x1 >> 8); const x53: u8 = @intCast(u8, (x52 & @intCast(u32, 0xff))); const x54: u32 = (x52 >> 8); const x55: u8 = @intCast(u8, (x54 & @intCast(u32, 0xff))); const x56: u8 = @intCast(u8, (x54 >> 8)); out1[0] = x9; out1[1] = x11; out1[2] = x13; out1[3] = x14; out1[4] = x15; out1[5] = x17; out1[6] = x19; out1[7] = x20; out1[8] = x21; out1[9] = x23; out1[10] = x25; out1[11] = x26; out1[12] = x27; out1[13] = x29; out1[14] = x31; out1[15] = x32; out1[16] = x33; out1[17] = x35; out1[18] = x37; out1[19] = x38; out1[20] = x39; out1[21] = x41; out1[22] = x43; out1[23] = x44; out1[24] = x45; out1[25] = x47; out1[26] = x49; out1[27] = x50; out1[28] = x51; out1[29] = x53; out1[30] = x55; out1[31] = x56; } /// The function fiatSecp256k1FromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1FromBytes(out1: *[8]u32, arg1: [32]u8) void { const x1: u32 = (@intCast(u32, (arg1[31])) << 24); const x2: u32 = (@intCast(u32, (arg1[30])) << 16); const x3: u32 = (@intCast(u32, (arg1[29])) << 8); const x4: u8 = (arg1[28]); const x5: u32 = (@intCast(u32, (arg1[27])) << 24); const x6: u32 = (@intCast(u32, (arg1[26])) << 16); const x7: u32 = (@intCast(u32, (arg1[25])) << 8); const x8: u8 = (arg1[24]); const x9: u32 = (@intCast(u32, (arg1[23])) << 24); const x10: u32 = (@intCast(u32, (arg1[22])) << 16); const x11: u32 = (@intCast(u32, (arg1[21])) << 8); const x12: u8 = (arg1[20]); const x13: u32 = (@intCast(u32, (arg1[19])) << 24); const x14: u32 = (@intCast(u32, (arg1[18])) << 16); const x15: u32 = (@intCast(u32, (arg1[17])) << 8); const x16: u8 = (arg1[16]); const x17: u32 = (@intCast(u32, (arg1[15])) << 24); const x18: u32 = (@intCast(u32, (arg1[14])) << 16); const x19: u32 = (@intCast(u32, (arg1[13])) << 8); const x20: u8 = (arg1[12]); const x21: u32 = (@intCast(u32, (arg1[11])) << 24); const x22: u32 = (@intCast(u32, (arg1[10])) << 16); const x23: u32 = (@intCast(u32, (arg1[9])) << 8); const x24: u8 = (arg1[8]); const x25: u32 = (@intCast(u32, (arg1[7])) << 24); const x26: u32 = (@intCast(u32, (arg1[6])) << 16); const x27: u32 = (@intCast(u32, (arg1[5])) << 8); const x28: u8 = (arg1[4]); const x29: u32 = (@intCast(u32, (arg1[3])) << 24); const x30: u32 = (@intCast(u32, (arg1[2])) << 16); const x31: u32 = (@intCast(u32, (arg1[1])) << 8); const x32: u8 = (arg1[0]); const x33: u32 = (x31 + @intCast(u32, x32)); const x34: u32 = (x30 + x33); const x35: u32 = (x29 + x34); const x36: u32 = (x27 + @intCast(u32, x28)); const x37: u32 = (x26 + x36); const x38: u32 = (x25 + x37); const x39: u32 = (x23 + @intCast(u32, x24)); const x40: u32 = (x22 + x39); const x41: u32 = (x21 + x40); const x42: u32 = (x19 + @intCast(u32, x20)); const x43: u32 = (x18 + x42); const x44: u32 = (x17 + x43); const x45: u32 = (x15 + @intCast(u32, x16)); const x46: u32 = (x14 + x45); const x47: u32 = (x13 + x46); const x48: u32 = (x11 + @intCast(u32, x12)); const x49: u32 = (x10 + x48); const x50: u32 = (x9 + x49); const x51: u32 = (x7 + @intCast(u32, x8)); const x52: u32 = (x6 + x51); const x53: u32 = (x5 + x52); const x54: u32 = (x3 + @intCast(u32, x4)); const x55: u32 = (x2 + x54); const x56: u32 = (x1 + x55); out1[0] = x35; out1[1] = x38; out1[2] = x41; out1[3] = x44; out1[4] = x47; out1[5] = x50; out1[6] = x53; out1[7] = x56; } /// The function fiatSecp256k1SetOne returns the field element one in the Montgomery domain. /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1SetOne(out1: *[8]u32) void { out1[0] = 0x3d1; out1[1] = @intCast(u32, 0x1); out1[2] = @intCast(u32, 0x0); out1[3] = @intCast(u32, 0x0); out1[4] = @intCast(u32, 0x0); out1[5] = @intCast(u32, 0x0); out1[6] = @intCast(u32, 0x0); out1[7] = @intCast(u32, 0x0); } /// The function fiatSecp256k1Msat returns the saturated representation of the prime modulus. /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Msat(out1: *[9]u32) void { out1[0] = 0xfffffc2f; out1[1] = 0xfffffffe; out1[2] = 0xffffffff; out1[3] = 0xffffffff; out1[4] = 0xffffffff; out1[5] = 0xffffffff; out1[6] = 0xffffffff; out1[7] = 0xffffffff; out1[8] = @intCast(u32, 0x0); } /// The function fiatSecp256k1Divstep computes a divstep. /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffff] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1Divstep(out1: *u32, out2: *[9]u32, out3: *[9]u32, out4: *[8]u32, out5: *[8]u32, arg1: u32, arg2: [9]u32, arg3: [9]u32, arg4: [8]u32, arg5: [8]u32) void { var x1: u32 = undefined; var x2: u1 = undefined; fiatSecp256k1AddcarryxU32(&x1, &x2, 0x0, (~arg1), @intCast(u32, 0x1)); const x3: u1 = (@intCast(u1, (x1 >> 31)) & @intCast(u1, ((arg3[0]) & @intCast(u32, 0x1)))); var x4: u32 = undefined; var x5: u1 = undefined; fiatSecp256k1AddcarryxU32(&x4, &x5, 0x0, (~arg1), @intCast(u32, 0x1)); var x6: u32 = undefined; fiatSecp256k1CmovznzU32(&x6, x3, arg1, x4); var x7: u32 = undefined; fiatSecp256k1CmovznzU32(&x7, x3, (arg2[0]), (arg3[0])); var x8: u32 = undefined; fiatSecp256k1CmovznzU32(&x8, x3, (arg2[1]), (arg3[1])); var x9: u32 = undefined; fiatSecp256k1CmovznzU32(&x9, x3, (arg2[2]), (arg3[2])); var x10: u32 = undefined; fiatSecp256k1CmovznzU32(&x10, x3, (arg2[3]), (arg3[3])); var x11: u32 = undefined; fiatSecp256k1CmovznzU32(&x11, x3, (arg2[4]), (arg3[4])); var x12: u32 = undefined; fiatSecp256k1CmovznzU32(&x12, x3, (arg2[5]), (arg3[5])); var x13: u32 = undefined; fiatSecp256k1CmovznzU32(&x13, x3, (arg2[6]), (arg3[6])); var x14: u32 = undefined; fiatSecp256k1CmovznzU32(&x14, x3, (arg2[7]), (arg3[7])); var x15: u32 = undefined; fiatSecp256k1CmovznzU32(&x15, x3, (arg2[8]), (arg3[8])); var x16: u32 = undefined; var x17: u1 = undefined; fiatSecp256k1AddcarryxU32(&x16, &x17, 0x0, @intCast(u32, 0x1), (~(arg2[0]))); var x18: u32 = undefined; var x19: u1 = undefined; fiatSecp256k1AddcarryxU32(&x18, &x19, x17, @intCast(u32, 0x0), (~(arg2[1]))); var x20: u32 = undefined; var x21: u1 = undefined; fiatSecp256k1AddcarryxU32(&x20, &x21, x19, @intCast(u32, 0x0), (~(arg2[2]))); var x22: u32 = undefined; var x23: u1 = undefined; fiatSecp256k1AddcarryxU32(&x22, &x23, x21, @intCast(u32, 0x0), (~(arg2[3]))); var x24: u32 = undefined; var x25: u1 = undefined; fiatSecp256k1AddcarryxU32(&x24, &x25, x23, @intCast(u32, 0x0), (~(arg2[4]))); var x26: u32 = undefined; var x27: u1 = undefined; fiatSecp256k1AddcarryxU32(&x26, &x27, x25, @intCast(u32, 0x0), (~(arg2[5]))); var x28: u32 = undefined; var x29: u1 = undefined; fiatSecp256k1AddcarryxU32(&x28, &x29, x27, @intCast(u32, 0x0), (~(arg2[6]))); var x30: u32 = undefined; var x31: u1 = undefined; fiatSecp256k1AddcarryxU32(&x30, &x31, x29, @intCast(u32, 0x0), (~(arg2[7]))); var x32: u32 = undefined; var x33: u1 = undefined; fiatSecp256k1AddcarryxU32(&x32, &x33, x31, @intCast(u32, 0x0), (~(arg2[8]))); var x34: u32 = undefined; fiatSecp256k1CmovznzU32(&x34, x3, (arg3[0]), x16); var x35: u32 = undefined; fiatSecp256k1CmovznzU32(&x35, x3, (arg3[1]), x18); var x36: u32 = undefined; fiatSecp256k1CmovznzU32(&x36, x3, (arg3[2]), x20); var x37: u32 = undefined; fiatSecp256k1CmovznzU32(&x37, x3, (arg3[3]), x22); var x38: u32 = undefined; fiatSecp256k1CmovznzU32(&x38, x3, (arg3[4]), x24); var x39: u32 = undefined; fiatSecp256k1CmovznzU32(&x39, x3, (arg3[5]), x26); var x40: u32 = undefined; fiatSecp256k1CmovznzU32(&x40, x3, (arg3[6]), x28); var x41: u32 = undefined; fiatSecp256k1CmovznzU32(&x41, x3, (arg3[7]), x30); var x42: u32 = undefined; fiatSecp256k1CmovznzU32(&x42, x3, (arg3[8]), x32); var x43: u32 = undefined; fiatSecp256k1CmovznzU32(&x43, x3, (arg4[0]), (arg5[0])); var x44: u32 = undefined; fiatSecp256k1CmovznzU32(&x44, x3, (arg4[1]), (arg5[1])); var x45: u32 = undefined; fiatSecp256k1CmovznzU32(&x45, x3, (arg4[2]), (arg5[2])); var x46: u32 = undefined; fiatSecp256k1CmovznzU32(&x46, x3, (arg4[3]), (arg5[3])); var x47: u32 = undefined; fiatSecp256k1CmovznzU32(&x47, x3, (arg4[4]), (arg5[4])); var x48: u32 = undefined; fiatSecp256k1CmovznzU32(&x48, x3, (arg4[5]), (arg5[5])); var x49: u32 = undefined; fiatSecp256k1CmovznzU32(&x49, x3, (arg4[6]), (arg5[6])); var x50: u32 = undefined; fiatSecp256k1CmovznzU32(&x50, x3, (arg4[7]), (arg5[7])); var x51: u32 = undefined; var x52: u1 = undefined; fiatSecp256k1AddcarryxU32(&x51, &x52, 0x0, x43, x43); var x53: u32 = undefined; var x54: u1 = undefined; fiatSecp256k1AddcarryxU32(&x53, &x54, x52, x44, x44); var x55: u32 = undefined; var x56: u1 = undefined; fiatSecp256k1AddcarryxU32(&x55, &x56, x54, x45, x45); var x57: u32 = undefined; var x58: u1 = undefined; fiatSecp256k1AddcarryxU32(&x57, &x58, x56, x46, x46); var x59: u32 = undefined; var x60: u1 = undefined; fiatSecp256k1AddcarryxU32(&x59, &x60, x58, x47, x47); var x61: u32 = undefined; var x62: u1 = undefined; fiatSecp256k1AddcarryxU32(&x61, &x62, x60, x48, x48); var x63: u32 = undefined; var x64: u1 = undefined; fiatSecp256k1AddcarryxU32(&x63, &x64, x62, x49, x49); var x65: u32 = undefined; var x66: u1 = undefined; fiatSecp256k1AddcarryxU32(&x65, &x66, x64, x50, x50); var x67: u32 = undefined; var x68: u1 = undefined; fiatSecp256k1SubborrowxU32(&x67, &x68, 0x0, x51, 0xfffffc2f); var x69: u32 = undefined; var x70: u1 = undefined; fiatSecp256k1SubborrowxU32(&x69, &x70, x68, x53, 0xfffffffe); var x71: u32 = undefined; var x72: u1 = undefined; fiatSecp256k1SubborrowxU32(&x71, &x72, x70, x55, 0xffffffff); var x73: u32 = undefined; var x74: u1 = undefined; fiatSecp256k1SubborrowxU32(&x73, &x74, x72, x57, 0xffffffff); var x75: u32 = undefined; var x76: u1 = undefined; fiatSecp256k1SubborrowxU32(&x75, &x76, x74, x59, 0xffffffff); var x77: u32 = undefined; var x78: u1 = undefined; fiatSecp256k1SubborrowxU32(&x77, &x78, x76, x61, 0xffffffff); var x79: u32 = undefined; var x80: u1 = undefined; fiatSecp256k1SubborrowxU32(&x79, &x80, x78, x63, 0xffffffff); var x81: u32 = undefined; var x82: u1 = undefined; fiatSecp256k1SubborrowxU32(&x81, &x82, x80, x65, 0xffffffff); var x83: u32 = undefined; var x84: u1 = undefined; fiatSecp256k1SubborrowxU32(&x83, &x84, x82, @intCast(u32, x66), @intCast(u32, 0x0)); const x85: u32 = (arg4[7]); const x86: u32 = (arg4[6]); const x87: u32 = (arg4[5]); const x88: u32 = (arg4[4]); const x89: u32 = (arg4[3]); const x90: u32 = (arg4[2]); const x91: u32 = (arg4[1]); const x92: u32 = (arg4[0]); var x93: u32 = undefined; var x94: u1 = undefined; fiatSecp256k1SubborrowxU32(&x93, &x94, 0x0, @intCast(u32, 0x0), x92); var x95: u32 = undefined; var x96: u1 = undefined; fiatSecp256k1SubborrowxU32(&x95, &x96, x94, @intCast(u32, 0x0), x91); var x97: u32 = undefined; var x98: u1 = undefined; fiatSecp256k1SubborrowxU32(&x97, &x98, x96, @intCast(u32, 0x0), x90); var x99: u32 = undefined; var x100: u1 = undefined; fiatSecp256k1SubborrowxU32(&x99, &x100, x98, @intCast(u32, 0x0), x89); var x101: u32 = undefined; var x102: u1 = undefined; fiatSecp256k1SubborrowxU32(&x101, &x102, x100, @intCast(u32, 0x0), x88); var x103: u32 = undefined; var x104: u1 = undefined; fiatSecp256k1SubborrowxU32(&x103, &x104, x102, @intCast(u32, 0x0), x87); var x105: u32 = undefined; var x106: u1 = undefined; fiatSecp256k1SubborrowxU32(&x105, &x106, x104, @intCast(u32, 0x0), x86); var x107: u32 = undefined; var x108: u1 = undefined; fiatSecp256k1SubborrowxU32(&x107, &x108, x106, @intCast(u32, 0x0), x85); var x109: u32 = undefined; fiatSecp256k1CmovznzU32(&x109, x108, @intCast(u32, 0x0), 0xffffffff); var x110: u32 = undefined; var x111: u1 = undefined; fiatSecp256k1AddcarryxU32(&x110, &x111, 0x0, x93, (x109 & 0xfffffc2f)); var x112: u32 = undefined; var x113: u1 = undefined; fiatSecp256k1AddcarryxU32(&x112, &x113, x111, x95, (x109 & 0xfffffffe)); var x114: u32 = undefined; var x115: u1 = undefined; fiatSecp256k1AddcarryxU32(&x114, &x115, x113, x97, x109); var x116: u32 = undefined; var x117: u1 = undefined; fiatSecp256k1AddcarryxU32(&x116, &x117, x115, x99, x109); var x118: u32 = undefined; var x119: u1 = undefined; fiatSecp256k1AddcarryxU32(&x118, &x119, x117, x101, x109); var x120: u32 = undefined; var x121: u1 = undefined; fiatSecp256k1AddcarryxU32(&x120, &x121, x119, x103, x109); var x122: u32 = undefined; var x123: u1 = undefined; fiatSecp256k1AddcarryxU32(&x122, &x123, x121, x105, x109); var x124: u32 = undefined; var x125: u1 = undefined; fiatSecp256k1AddcarryxU32(&x124, &x125, x123, x107, x109); var x126: u32 = undefined; fiatSecp256k1CmovznzU32(&x126, x3, (arg5[0]), x110); var x127: u32 = undefined; fiatSecp256k1CmovznzU32(&x127, x3, (arg5[1]), x112); var x128: u32 = undefined; fiatSecp256k1CmovznzU32(&x128, x3, (arg5[2]), x114); var x129: u32 = undefined; fiatSecp256k1CmovznzU32(&x129, x3, (arg5[3]), x116); var x130: u32 = undefined; fiatSecp256k1CmovznzU32(&x130, x3, (arg5[4]), x118); var x131: u32 = undefined; fiatSecp256k1CmovznzU32(&x131, x3, (arg5[5]), x120); var x132: u32 = undefined; fiatSecp256k1CmovznzU32(&x132, x3, (arg5[6]), x122); var x133: u32 = undefined; fiatSecp256k1CmovznzU32(&x133, x3, (arg5[7]), x124); const x134: u1 = @intCast(u1, (x34 & @intCast(u32, 0x1))); var x135: u32 = undefined; fiatSecp256k1CmovznzU32(&x135, x134, @intCast(u32, 0x0), x7); var x136: u32 = undefined; fiatSecp256k1CmovznzU32(&x136, x134, @intCast(u32, 0x0), x8); var x137: u32 = undefined; fiatSecp256k1CmovznzU32(&x137, x134, @intCast(u32, 0x0), x9); var x138: u32 = undefined; fiatSecp256k1CmovznzU32(&x138, x134, @intCast(u32, 0x0), x10); var x139: u32 = undefined; fiatSecp256k1CmovznzU32(&x139, x134, @intCast(u32, 0x0), x11); var x140: u32 = undefined; fiatSecp256k1CmovznzU32(&x140, x134, @intCast(u32, 0x0), x12); var x141: u32 = undefined; fiatSecp256k1CmovznzU32(&x141, x134, @intCast(u32, 0x0), x13); var x142: u32 = undefined; fiatSecp256k1CmovznzU32(&x142, x134, @intCast(u32, 0x0), x14); var x143: u32 = undefined; fiatSecp256k1CmovznzU32(&x143, x134, @intCast(u32, 0x0), x15); var x144: u32 = undefined; var x145: u1 = undefined; fiatSecp256k1AddcarryxU32(&x144, &x145, 0x0, x34, x135); var x146: u32 = undefined; var x147: u1 = undefined; fiatSecp256k1AddcarryxU32(&x146, &x147, x145, x35, x136); var x148: u32 = undefined; var x149: u1 = undefined; fiatSecp256k1AddcarryxU32(&x148, &x149, x147, x36, x137); var x150: u32 = undefined; var x151: u1 = undefined; fiatSecp256k1AddcarryxU32(&x150, &x151, x149, x37, x138); var x152: u32 = undefined; var x153: u1 = undefined; fiatSecp256k1AddcarryxU32(&x152, &x153, x151, x38, x139); var x154: u32 = undefined; var x155: u1 = undefined; fiatSecp256k1AddcarryxU32(&x154, &x155, x153, x39, x140); var x156: u32 = undefined; var x157: u1 = undefined; fiatSecp256k1AddcarryxU32(&x156, &x157, x155, x40, x141); var x158: u32 = undefined; var x159: u1 = undefined; fiatSecp256k1AddcarryxU32(&x158, &x159, x157, x41, x142); var x160: u32 = undefined; var x161: u1 = undefined; fiatSecp256k1AddcarryxU32(&x160, &x161, x159, x42, x143); var x162: u32 = undefined; fiatSecp256k1CmovznzU32(&x162, x134, @intCast(u32, 0x0), x43); var x163: u32 = undefined; fiatSecp256k1CmovznzU32(&x163, x134, @intCast(u32, 0x0), x44); var x164: u32 = undefined; fiatSecp256k1CmovznzU32(&x164, x134, @intCast(u32, 0x0), x45); var x165: u32 = undefined; fiatSecp256k1CmovznzU32(&x165, x134, @intCast(u32, 0x0), x46); var x166: u32 = undefined; fiatSecp256k1CmovznzU32(&x166, x134, @intCast(u32, 0x0), x47); var x167: u32 = undefined; fiatSecp256k1CmovznzU32(&x167, x134, @intCast(u32, 0x0), x48); var x168: u32 = undefined; fiatSecp256k1CmovznzU32(&x168, x134, @intCast(u32, 0x0), x49); var x169: u32 = undefined; fiatSecp256k1CmovznzU32(&x169, x134, @intCast(u32, 0x0), x50); var x170: u32 = undefined; var x171: u1 = undefined; fiatSecp256k1AddcarryxU32(&x170, &x171, 0x0, x126, x162); var x172: u32 = undefined; var x173: u1 = undefined; fiatSecp256k1AddcarryxU32(&x172, &x173, x171, x127, x163); var x174: u32 = undefined; var x175: u1 = undefined; fiatSecp256k1AddcarryxU32(&x174, &x175, x173, x128, x164); var x176: u32 = undefined; var x177: u1 = undefined; fiatSecp256k1AddcarryxU32(&x176, &x177, x175, x129, x165); var x178: u32 = undefined; var x179: u1 = undefined; fiatSecp256k1AddcarryxU32(&x178, &x179, x177, x130, x166); var x180: u32 = undefined; var x181: u1 = undefined; fiatSecp256k1AddcarryxU32(&x180, &x181, x179, x131, x167); var x182: u32 = undefined; var x183: u1 = undefined; fiatSecp256k1AddcarryxU32(&x182, &x183, x181, x132, x168); var x184: u32 = undefined; var x185: u1 = undefined; fiatSecp256k1AddcarryxU32(&x184, &x185, x183, x133, x169); var x186: u32 = undefined; var x187: u1 = undefined; fiatSecp256k1SubborrowxU32(&x186, &x187, 0x0, x170, 0xfffffc2f); var x188: u32 = undefined; var x189: u1 = undefined; fiatSecp256k1SubborrowxU32(&x188, &x189, x187, x172, 0xfffffffe); var x190: u32 = undefined; var x191: u1 = undefined; fiatSecp256k1SubborrowxU32(&x190, &x191, x189, x174, 0xffffffff); var x192: u32 = undefined; var x193: u1 = undefined; fiatSecp256k1SubborrowxU32(&x192, &x193, x191, x176, 0xffffffff); var x194: u32 = undefined; var x195: u1 = undefined; fiatSecp256k1SubborrowxU32(&x194, &x195, x193, x178, 0xffffffff); var x196: u32 = undefined; var x197: u1 = undefined; fiatSecp256k1SubborrowxU32(&x196, &x197, x195, x180, 0xffffffff); var x198: u32 = undefined; var x199: u1 = undefined; fiatSecp256k1SubborrowxU32(&x198, &x199, x197, x182, 0xffffffff); var x200: u32 = undefined; var x201: u1 = undefined; fiatSecp256k1SubborrowxU32(&x200, &x201, x199, x184, 0xffffffff); var x202: u32 = undefined; var x203: u1 = undefined; fiatSecp256k1SubborrowxU32(&x202, &x203, x201, @intCast(u32, x185), @intCast(u32, 0x0)); var x204: u32 = undefined; var x205: u1 = undefined; fiatSecp256k1AddcarryxU32(&x204, &x205, 0x0, x6, @intCast(u32, 0x1)); const x206: u32 = ((x144 >> 1) | ((x146 << 31) & 0xffffffff)); const x207: u32 = ((x146 >> 1) | ((x148 << 31) & 0xffffffff)); const x208: u32 = ((x148 >> 1) | ((x150 << 31) & 0xffffffff)); const x209: u32 = ((x150 >> 1) | ((x152 << 31) & 0xffffffff)); const x210: u32 = ((x152 >> 1) | ((x154 << 31) & 0xffffffff)); const x211: u32 = ((x154 >> 1) | ((x156 << 31) & 0xffffffff)); const x212: u32 = ((x156 >> 1) | ((x158 << 31) & 0xffffffff)); const x213: u32 = ((x158 >> 1) | ((x160 << 31) & 0xffffffff)); const x214: u32 = ((x160 & 0x80000000) | (x160 >> 1)); var x215: u32 = undefined; fiatSecp256k1CmovznzU32(&x215, x84, x67, x51); var x216: u32 = undefined; fiatSecp256k1CmovznzU32(&x216, x84, x69, x53); var x217: u32 = undefined; fiatSecp256k1CmovznzU32(&x217, x84, x71, x55); var x218: u32 = undefined; fiatSecp256k1CmovznzU32(&x218, x84, x73, x57); var x219: u32 = undefined; fiatSecp256k1CmovznzU32(&x219, x84, x75, x59); var x220: u32 = undefined; fiatSecp256k1CmovznzU32(&x220, x84, x77, x61); var x221: u32 = undefined; fiatSecp256k1CmovznzU32(&x221, x84, x79, x63); var x222: u32 = undefined; fiatSecp256k1CmovznzU32(&x222, x84, x81, x65); var x223: u32 = undefined; fiatSecp256k1CmovznzU32(&x223, x203, x186, x170); var x224: u32 = undefined; fiatSecp256k1CmovznzU32(&x224, x203, x188, x172); var x225: u32 = undefined; fiatSecp256k1CmovznzU32(&x225, x203, x190, x174); var x226: u32 = undefined; fiatSecp256k1CmovznzU32(&x226, x203, x192, x176); var x227: u32 = undefined; fiatSecp256k1CmovznzU32(&x227, x203, x194, x178); var x228: u32 = undefined; fiatSecp256k1CmovznzU32(&x228, x203, x196, x180); var x229: u32 = undefined; fiatSecp256k1CmovznzU32(&x229, x203, x198, x182); var x230: u32 = undefined; fiatSecp256k1CmovznzU32(&x230, x203, x200, x184); out1.* = x204; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out2[5] = x12; out2[6] = x13; out2[7] = x14; out2[8] = x15; out3[0] = x206; out3[1] = x207; out3[2] = x208; out3[3] = x209; out3[4] = x210; out3[5] = x211; out3[6] = x212; out3[7] = x213; out3[8] = x214; out4[0] = x215; out4[1] = x216; out4[2] = x217; out4[3] = x218; out4[4] = x219; out4[5] = x220; out4[6] = x221; out4[7] = x222; out5[0] = x223; out5[1] = x224; out5[2] = x225; out5[3] = x226; out5[4] = x227; out5[5] = x228; out5[6] = x229; out5[7] = x230; } /// The function fiatSecp256k1DivstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if (log2 m) + 1 < 46 then ⌊(49 * ((log2 m) + 1) + 80) / 17⌋ else ⌊(49 * ((log2 m) + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Input Bounds: /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] pub fn fiatSecp256k1DivstepPrecomp(out1: *[8]u32) void { out1[0] = 0x31525e0a; out1[1] = 0xf201a418; out1[2] = 0xcd648d85; out1[3] = 0x9953f9dd; out1[4] = 0x3db210a9; out1[5] = 0xe8602946; out1[6] = 0x4b03709; out1[7] = 0x24fb8a31; }
fiat-zig/src/secp256k1_32.zig
const std = @import("std"); const Instance = @import("Instance.zig"); const Context = @import("Context.zig"); fn drop_loop(ctx: Context, allocator: std.mem.Allocator) ?Instance { while (true) { const filename = ctx.wait_for_file() orelse return null; if (Instance.init(ctx, filename, allocator)) |instance| { return instance; } else |err| { const errstr = switch (err) { error.TextureError => "Probably a unsupported image format, try again with a JPEG or PNG", error.OutOfMemory => "Ran out of memory!", else => @errorName(err), //"Unkown error, check command prompt if available.", }; std.log.warn("drop error: {s}", .{errstr}); ctx.error_box(errstr); continue; } } } pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var imgFilename: ?[:0]const u8 = null; var args = std.process.args(); _ = args.skip(); while (args.next(allocator)) |argerr| { const arg = try argerr; defer allocator.free(arg); if (arg.len != 0 and arg[0] == '-') { // options? std.log.warn("unkown option \"{s}\"", .{arg}); return; } else { if (imgFilename != null) { std.log.warn("a file has already been read, ignoring \"{s}\"", .{arg}); continue; } imgFilename = try allocator.dupeZ(u8, arg); } } var ctx = try Context.init(); defer ctx.deinit(); if (imgFilename) |img| { defer allocator.free(img); var instance = try Instance.init(ctx, img, allocator); defer instance.deinit(); instance.main_loop(); } else { std.log.debug("No filename argument, starting drop file loop...", .{}); var instance = drop_loop(ctx, allocator) orelse return; defer instance.deinit(); instance.main_loop(); } }
src/main.zig
const std = @import("std"); const mem = std.mem; const trait = std.meta.trait; const assert = std.debug.assert; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; pub const SelfType = opaque {}; fn makeSelfPtr(ptr: anytype) *SelfType { if (comptime !trait.isSingleItemPtr(@TypeOf(ptr))) { @compileError("SelfType pointer initialization expects pointer parameter."); } const T = std.meta.Child(@TypeOf(ptr)); if (@sizeOf(T) > 0) { return @ptrCast(*SelfType, ptr); } else { return undefined; } } fn selfPtrAs(self: *SelfType, comptime T: type) *T { if (@sizeOf(T) > 0) { return @alignCast(@alignOf(T), @ptrCast(*align(1) T, self)); } else { return undefined; } } fn constSelfPtrAs(self: *const SelfType, comptime T: type) *const T { if (@sizeOf(T) > 0) { return @alignCast(@alignOf(T), @ptrCast(*align(1) const T, self)); } else { return undefined; } } pub const Storage = struct { pub const Comptime = struct { erased_ptr: *SelfType, ImplType: type, fn makeInit(comptime TInterface: type) type { return struct { fn init(obj: anytype) !TInterface { const ImplType = PtrChildOrSelf(@TypeOf(obj)); comptime var obj_holder = obj; return TInterface{ .vtable_ptr = &comptime makeVTable(TInterface.VTable, ImplType), .storage = Comptime{ .erased_ptr = makeSelfPtr(&obj_holder), .ImplType = @TypeOf(obj), }, }; } }; } pub fn getSelfPtr(comptime self: *Comptime) *SelfType { return self.erased_ptr; } pub fn deinit(comptime self: Comptime) void { _ = self; } }; pub const NonOwning = struct { erased_ptr: *SelfType, fn makeInit(comptime TInterface: type) type { return struct { fn init(ptr: anytype) !TInterface { return TInterface{ .vtable_ptr = &comptime makeVTable(TInterface.VTable, PtrChildOrSelf(@TypeOf(ptr))), .storage = NonOwning{ .erased_ptr = makeSelfPtr(ptr), }, }; } }; } pub fn getSelfPtr(self: NonOwning) *SelfType { return self.erased_ptr; } pub fn deinit(self: NonOwning) void { _ = self; } }; pub const Owning = struct { allocator: *mem.Allocator, mem: []u8, fn makeInit(comptime TInterface: type) type { return struct { fn init(obj: anytype, allocator: *std.mem.Allocator) !TInterface { const AllocT = @TypeOf(obj); var ptr = try allocator.create(AllocT); ptr.* = obj; return TInterface{ .vtable_ptr = &comptime makeVTable(TInterface.VTable, PtrChildOrSelf(AllocT)), .storage = Owning{ .allocator = allocator, .mem = std.mem.asBytes(ptr)[0..], }, }; } }; } pub fn getSelfPtr(self: Owning) *SelfType { return makeSelfPtr(&self.mem[0]); } pub fn deinit(self: Owning) void { const result = self.allocator.shrinkBytes(self.mem, 0, 0, 0, 0); assert(result == 0); } }; pub fn Inline(comptime size: usize) type { return struct { const Self = @This(); mem: [size]u8, fn makeInit(comptime TInterface: type) type { return struct { fn init(value: anytype) !TInterface { const ImplSize = @sizeOf(@TypeOf(value)); if (ImplSize > size) { @compileError("Type does not fit in inline storage."); } var self = Self{ .mem = undefined, }; if (ImplSize > 0) { std.mem.copy(u8, self.mem[0..], @ptrCast([*]const u8, &value)[0..ImplSize]); } return TInterface{ .vtable_ptr = &comptime makeVTable(TInterface.VTable, PtrChildOrSelf(@TypeOf(value))), .storage = self, }; } }; } pub fn getSelfPtr(self: *Self) *SelfType { return makeSelfPtr(&self.mem[0]); } pub fn deinit(self: Self) void { _ = self; } }; } pub fn InlineOrOwning(comptime size: usize) type { return struct { const Self = @This(); data: union(enum) { Inline: Inline(size), Owning: Owning, }, pub fn init(args: anytype) !Self { if (args.len != 2) { @compileError("InlineOrOwning storage expected a 2-tuple in initialization."); } const ImplSize = @sizeOf(@TypeOf(args[0])); if (ImplSize > size) { return Self{ .data = .{ .Owning = try Owning.init(args), }, }; } else { return Self{ .data = .{ .Inline = try Inline(size).init(.{args[0]}), }, }; } } pub fn getSelfPtr(self: *Self) *SelfType { return switch (self.data) { .Inline => |*i| i.getSelfPtr(), .Owning => |*o| o.getSelfPtr(), }; } pub fn deinit(self: Self) void { switch (self.data) { .Inline => |i| i.deinit(), .Owning => |o| o.deinit(), } } }; } }; fn PtrChildOrSelf(comptime T: type) type { if (comptime trait.isSingleItemPtr(T)) { return std.meta.Child(T); } return T; } const GenCallType = enum { BothAsync, BothBlocking, AsyncCallsBlocking, BlockingCallsAsync, }; fn makeCall( comptime name: []const u8, comptime CurrSelfType: type, comptime Return: type, comptime ImplT: type, comptime call_type: GenCallType, self_ptr: CurrSelfType, args: anytype, ) Return { const is_const = CurrSelfType == *const SelfType; const self = if (is_const) constSelfPtrAs(self_ptr, ImplT) else selfPtrAs(self_ptr, ImplT); const fptr = @field(ImplT, name); const first_arg_ptr = comptime std.meta.trait.is(.Pointer)(@typeInfo(@TypeOf(fptr)).Fn.args[0].arg_type.?); const self_arg = if (first_arg_ptr) .{self} else .{self.*}; return switch (call_type) { .BothBlocking => @call(.{ .modifier = .always_inline }, fptr, self_arg ++ args), .AsyncCallsBlocking, .BothAsync => await @call(.{ .modifier = .async_kw }, fptr, self_arg ++ args), .BlockingCallsAsync => @compileError("Trying to implement blocking virtual function " ++ name ++ " with async implementation."), }; } fn getFunctionFromImpl(comptime name: []const u8, comptime FnT: type, comptime ImplT: type) ?FnT { const our_cc = @typeInfo(FnT).Fn.calling_convention; // Find the candidate in the implementation type. for (std.meta.declarations(ImplT)) |decl| { if (std.mem.eql(u8, name, decl.name)) { switch (decl.data) { .Fn => |fn_decl| { const args = @typeInfo(fn_decl.fn_type).Fn.args; if (args.len == 0) { return @field(ImplT, name); } if (args.len > 0) { const arg0_type = args[0].arg_type.?; const is_method = arg0_type == ImplT or arg0_type == *ImplT or arg0_type == *const ImplT; const candidate_cc = @typeInfo(fn_decl.fn_type).Fn.calling_convention; switch (candidate_cc) { .Async, .Unspecified => {}, else => return null, } const Return = @typeInfo(FnT).Fn.return_type orelse noreturn; const CurrSelfType = @typeInfo(FnT).Fn.args[0].arg_type.?; const call_type: GenCallType = switch (our_cc) { .Async => if (candidate_cc == .Async) .BothAsync else .AsyncCallsBlocking, .Unspecified => if (candidate_cc == .Unspecified) .BothBlocking else .BlockingCallsAsync, else => unreachable, }; if (!is_method) { return @field(ImplT, name); } // TODO: Make this less hacky somehow? // We need some new feature to do so unfortunately. return switch (args.len) { 1 => struct { fn impl(self_ptr: CurrSelfType) callconv(our_cc) Return { return @call(.{ .modifier = .always_inline }, makeCall, .{ name, CurrSelfType, Return, ImplT, call_type, self_ptr, .{} }); } }.impl, 2 => struct { fn impl(self_ptr: CurrSelfType, arg: args[1].arg_type.?) callconv(our_cc) Return { return @call(.{ .modifier = .always_inline }, makeCall, .{ name, CurrSelfType, Return, ImplT, call_type, self_ptr, .{arg} }); } }.impl, 3 => struct { fn impl(self_ptr: CurrSelfType, arg1: args[1].arg_type.?, arg2: args[2].arg_type.?) callconv(our_cc) Return { return @call(.{ .modifier = .always_inline }, makeCall, .{ name, CurrSelfType, Return, ImplT, call_type, self_ptr, .{ arg1, arg2 } }); } }.impl, 4 => struct { fn impl(self_ptr: CurrSelfType, arg1: args[1].arg_type.?, arg2: args[2].arg_type.?, arg3: args[3].arg_type.?) callconv(our_cc) Return { return @call(.{ .modifier = .always_inline }, makeCall, .{ name, CurrSelfType, Return, ImplT, call_type, self_ptr, .{ arg1, arg2, arg3 } }); } }.impl, 5 => struct { fn impl(self_ptr: CurrSelfType, arg1: args[1].arg_type.?, arg2: args[2].arg_type.?, arg3: args[3].arg_type.?, arg4: args[4].arg_type.?) callconv(our_cc) Return { return @call(.{ .modifier = .always_inline }, makeCall, .{ name, CurrSelfType, Return, ImplT, call_type, self_ptr, .{ arg1, arg2, arg3, arg4 } }); } }.impl, 6 => struct { fn impl(self_ptr: CurrSelfType, arg1: args[1].arg_type.?, arg2: args[2].arg_type.?, arg3: args[3].arg_type.?, arg4: args[4].arg_type.?, arg5: args[5].arg_type.?) callconv(our_cc) Return { return @call(.{ .modifier = .always_inline }, makeCall, .{ name, CurrSelfType, Return, ImplT, call_type, self_ptr, .{ arg1, arg2, arg3, arg4, arg5 } }); } }.impl, else => @compileError("Unsupported number of arguments, please provide a manually written vtable."), }; } }, else => return null, } } } return null; } fn makeVTable(comptime VTableT: type, comptime ImplT: type) VTableT { if (comptime !trait.isContainer(ImplT)) { @compileError("Type '" ++ @typeName(ImplT) ++ "' must be a container to implement interface."); } var vtable: VTableT = undefined; for (std.meta.fields(VTableT)) |field| { var fn_type = field.field_type; const is_optional = trait.is(.Optional)(fn_type); if (is_optional) { fn_type = std.meta.Child(fn_type); } const candidate = comptime getFunctionFromImpl(field.name, fn_type, ImplT); if (candidate == null and !is_optional) { @compileError("Type '" ++ @typeName(ImplT) ++ "' does not implement non optional function '" ++ field.name ++ "'."); } else if (!is_optional) { @field(vtable, field.name) = candidate.?; } else { @field(vtable, field.name) = candidate; } } return vtable; } fn checkVtableType(comptime VTableT: type) void { if (comptime !trait.is(.Struct)(VTableT)) { @compileError("VTable type " ++ @typeName(VTableT) ++ " must be a struct."); } for (std.meta.declarations(VTableT)) |decl| { switch (decl.data) { .Fn => @compileError("VTable type defines method '" ++ decl.name ++ "'."), .Type, .Var => {}, } } for (std.meta.fields(VTableT)) |field| { var field_type = field.field_type; if (trait.is(.Optional)(field_type)) { field_type = std.meta.Child(field_type); } if (!trait.is(.Fn)(field_type)) { @compileError("VTable type defines non function field '" ++ field.name ++ "'."); } const type_info = @typeInfo(field_type); if (type_info.Fn.is_generic) { @compileError("Virtual function '" ++ field.name ++ "' cannot be generic."); } switch (type_info.Fn.calling_convention) { .Unspecified, .Async => {}, else => @compileError("Virtual function's '" ++ field.name ++ "' calling convention is not default or async."), } } } fn vtableHasMethod(comptime VTableT: type, comptime name: []const u8, is_optional: *bool, is_async: *bool, is_method: *bool) bool { for (std.meta.fields(VTableT)) |field| { if (std.mem.eql(u8, name, field.name)) { is_optional.* = trait.is(.Optional)(field.field_type); const fn_typeinfo = @typeInfo(if (is_optional.*) std.meta.Child(field.field_type) else field.field_type).Fn; is_async.* = fn_typeinfo.calling_convention == .Async; is_method.* = fn_typeinfo.args.len > 0 and blk: { const first_arg_type = fn_typeinfo.args[0].arg_type.?; break :blk first_arg_type == *SelfType or first_arg_type == *const SelfType; }; return true; } } return false; } fn VTableReturnType(comptime VTableT: type, comptime name: []const u8) type { for (std.meta.fields(VTableT)) |field| { if (std.mem.eql(u8, name, field.name)) { const is_optional = trait.is(.Optional)(field.field_type); var fn_ret_type = (if (is_optional) @typeInfo(std.meta.Child(field.field_type)).Fn.return_type else @typeInfo(field.field_type).Fn.return_type) orelse noreturn; if (is_optional) { return ?fn_ret_type; } return fn_ret_type; } } @compileError("VTable type '" ++ @typeName(VTableT) ++ "' has no virtual function '" ++ name ++ "'."); } pub fn Interface(comptime VTableT: type, comptime StorageT: type) type { comptime checkVtableType(VTableT); const stack_size: usize = if (@hasDecl(VTableT, "async_call_stack_size")) VTableT.async_call_stack_size else 1 * 1024 * 1024; return struct { vtable_ptr: *const VTableT, storage: StorageT, const Self = @This(); const VTable = VTableT; const Storage = StorageT; pub const init = StorageT.makeInit(Self).init; pub fn initWithVTable(vtable_ptr: *const VTableT, args: anytype) !Self { return .{ .vtable_ptr = vtable_ptr, .storage = try init(args), }; } pub fn call(self: anytype, comptime name: []const u8, args: anytype) VTableReturnType(VTableT, name) { comptime var is_optional = true; comptime var is_async = true; comptime var is_method = true; comptime assert(vtableHasMethod(VTableT, name, &is_optional, &is_async, &is_method)); const fn_ptr = if (is_optional) blk: { const val = @field(self.vtable_ptr, name); if (val) |v| break :blk v; return null; } else @field(self.vtable_ptr, name); if (is_method) { const self_ptr = self.storage.getSelfPtr(); const new_args = .{self_ptr}; if (!is_async) { return @call(.{}, fn_ptr, new_args ++ args); } else { var stack_frame: [stack_size]u8 align(std.Target.stack_align) = undefined; return await @asyncCall(&stack_frame, {}, fn_ptr, new_args ++ args); } } else { if (!is_async) { return @call(.{}, fn_ptr, args); } else { var stack_frame: [stack_size]u8 align(std.Target.stack_align) = undefined; return await @asyncCall(&stack_frame, {}, fn_ptr, args); } } } pub fn deinit(self: Self) void { self.storage.deinit(); } }; }
interface.zig
const std = @import("std"); const imgui = @import("imgui"); const sdl = @import("sdl"); const gk = @import("../gamekit.zig"); pub const Events = struct { mouse_cursors: [imgui.ImGuiMouseCursor_COUNT]?*sdl.SDL_Cursor = undefined, mouse_button_state: [4]bool = undefined, global_time: u64 = 0, var clipboard_text: [*c]u8 = null; pub fn init() Events { var io = imgui.igGetIO(); io.BackendFlags |= imgui.ImGuiBackendFlags_HasMouseCursors; io.BackendFlags |= imgui.ImGuiBackendFlags_HasSetMousePos; io.KeyMap[imgui.ImGuiKey_Tab] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_TAB); io.KeyMap[imgui.ImGuiKey_LeftArrow] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_LEFT); io.KeyMap[imgui.ImGuiKey_RightArrow] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_RIGHT); io.KeyMap[imgui.ImGuiKey_UpArrow] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_UP); io.KeyMap[imgui.ImGuiKey_DownArrow] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_DOWN); io.KeyMap[imgui.ImGuiKey_PageUp] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_PAGEUP); io.KeyMap[imgui.ImGuiKey_PageDown] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_PAGEDOWN); io.KeyMap[imgui.ImGuiKey_Home] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_HOME); io.KeyMap[imgui.ImGuiKey_End] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_END); io.KeyMap[imgui.ImGuiKey_Insert] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_INSERT); io.KeyMap[imgui.ImGuiKey_Delete] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_DELETE); io.KeyMap[imgui.ImGuiKey_Backspace] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_BACKSPACE); io.KeyMap[imgui.ImGuiKey_Space] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_SPACE); io.KeyMap[imgui.ImGuiKey_Enter] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_RETURN); io.KeyMap[imgui.ImGuiKey_Escape] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_ESCAPE); io.KeyMap[imgui.ImGuiKey_KeyPadEnter] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_RETURN2); io.KeyMap[imgui.ImGuiKey_A] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_A); io.KeyMap[imgui.ImGuiKey_C] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_C); io.KeyMap[imgui.ImGuiKey_V] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_V); io.KeyMap[imgui.ImGuiKey_X] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_X); io.KeyMap[imgui.ImGuiKey_Y] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_Y); io.KeyMap[imgui.ImGuiKey_Z] = @enumToInt(sdl.SDL_Scancode.SDL_SCANCODE_Z); io.SetClipboardTextFn = setClipboardTextFn; io.GetClipboardTextFn = getClipboardTextFn; var self = Events{}; self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_Arrow)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_ARROW); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_TextInput)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_IBEAM); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_ResizeAll)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_SIZEALL); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_ResizeNS)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_SIZENS); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_ResizeEW)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_SIZEWE); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_ResizeNESW)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_SIZENESW); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_ResizeNWSE)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_SIZENWSE); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_Hand)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_HAND); self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_NotAllowed)] = sdl.SDL_CreateSystemCursor(sdl.SDL_SystemCursor.SDL_SYSTEM_CURSOR_NO); // TODO: ImGui_ImplSDL2_UpdateMonitors // TODO: ImGui_ImplSDL2_InitPlatformInterface if ((io.ConfigFlags & imgui.ImGuiConfigFlags_ViewportsEnable) != 0 and (io.BackendFlags & imgui.ImGuiBackendFlags_PlatformHasViewports) != 0) { // var main_vp = imgui.igGetMainViewport(); // main_vp.PlatformHandle = window; //init_platform_interface(window); } return self; } pub fn deinit(self: Events) void { if (clipboard_text) |txt| sdl.SDL_free(txt); // Destroy SDL mouse cursors for (self.mouse_cursors) |cursor| { sdl.SDL_FreeCursor(cursor); } } fn getClipboardTextFn(ctx: ?*anyopaque) callconv(.C) [*c]const u8 { _ = ctx; if (clipboard_text) |txt| { sdl.SDL_free(txt); clipboard_text = null; } clipboard_text = sdl.SDL_GetClipboardText(); return clipboard_text; } fn setClipboardTextFn(ctx: ?*anyopaque, text: [*c]const u8) callconv(.C) void { _ = ctx; _ = sdl.SDL_SetClipboardText(text); } pub fn newFrame( self: *Events, window: *sdl.SDL_Window, ) void { var win_size = gk.window.size(); var drawable_size = gk.window.drawableSize(); const io = imgui.igGetIO(); io.DisplaySize = imgui.ImVec2{ .x = @intToFloat(f32, win_size.w), .y = @intToFloat(f32, win_size.h) }; if (win_size.w > 0 and win_size.h > 0) { io.DisplayFramebufferScale = imgui.ImVec2{ .x = @intToFloat(f32, drawable_size.w) / @intToFloat(f32, win_size.w), .y = @intToFloat(f32, drawable_size.h) / @intToFloat(f32, win_size.h), }; } const frequency = sdl.SDL_GetPerformanceFrequency(); const current_time = sdl.SDL_GetPerformanceCounter(); io.DeltaTime = if (self.global_time > 0) @floatCast(f32, (@intToFloat(f64, current_time - self.global_time)) / @intToFloat(f64, frequency)) else @as(f32, 1 / 60); self.global_time = current_time; // ImGui_ImplSDL2_UpdateMousePosAndButtons if (io.WantSetMousePos) { if ((io.ConfigFlags & imgui.ImGuiConfigFlags_ViewportsEnable) != 0) { _ = sdl.SDL_WarpMouseGlobal(@floatToInt(c_int, io.MousePos.x), @floatToInt(c_int, io.MousePos.y)); } else { _ = sdl.SDL_WarpMouseInWindow(window, @floatToInt(c_int, io.MousePos.x), @floatToInt(c_int, io.MousePos.y)); } } // Set Dear ImGui mouse pos from OS mouse pos + get buttons. (this is the common behavior) var mouse_x_local: c_int = undefined; var mouse_y_local: c_int = undefined; const mouse_buttons = sdl.SDL_GetMouseState(&mouse_x_local, &mouse_y_local); io.MouseDown[0] = self.mouse_button_state[0] or sdlButton(mouse_buttons, 1); io.MouseDown[1] = self.mouse_button_state[1] or sdlButton(mouse_buttons, 3); io.MouseDown[2] = self.mouse_button_state[2] or sdlButton(mouse_buttons, 2); self.mouse_button_state[0] = false; self.mouse_button_state[1] = false; self.mouse_button_state[2] = false; var mouse_x_global: c_int = undefined; var mouse_y_global: c_int = undefined; _ = sdl.SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); if (io.ConfigFlags & imgui.ImGuiConfigFlags_ViewportsEnable != 0) { std.log.warn("viewports not implemented\n", .{}); } else if (sdl.SDL_GetWindowFlags(window) | @intCast(u32, @enumToInt(sdl.SDL_WindowFlags.SDL_WINDOW_INPUT_FOCUS)) != 1) { var win_x: i32 = undefined; var win_y: i32 = undefined; sdl.SDL_GetWindowPosition(window, &win_x, &win_y); io.MousePos = imgui.ImVec2{ .x = @intToFloat(f32, mouse_x_global - win_x), .y = @intToFloat(f32, mouse_y_global - win_y), }; } // ImGui_ImplSDL2_UpdateMouseCursor if (io.ConfigFlags & imgui.ImGuiConfigFlags_NoMouseCursorChange == 0) { const cursor = imgui.igGetMouseCursor(); if (io.MouseDrawCursor or cursor == imgui.ImGuiMouseCursor_None) { _ = sdl.SDL_ShowCursor(sdl.SDL_FALSE); } else { sdl.SDL_SetCursor(self.mouse_cursors[@intCast(usize, cursor)] orelse self.mouse_cursors[@intCast(usize, imgui.ImGuiMouseCursor_Arrow)].?); _ = sdl.SDL_ShowCursor(sdl.SDL_TRUE); } } // TODO: ImGui_ImplSDL2_UpdateGamepads } // Mimics the SDL_BUTTON macro and does the button down check fn sdlButton(mouse_buttons: u32, comptime button: u32) bool { return mouse_buttons & (1 << (button - 1)) != 0; } pub fn handleEvent(self: *Events, event: *sdl.SDL_Event) bool { switch (event.type) { sdl.SDL_MOUSEWHEEL => { const io = imgui.igGetIO(); if (event.wheel.x > 0) io.MouseWheelH -= 1; if (event.wheel.x < 0) io.MouseWheelH += 1; if (event.wheel.y > 0) io.MouseWheel += 1; if (event.wheel.y < 0) io.MouseWheel -= 1; return io.WantCaptureMouse; }, sdl.SDL_MOUSEBUTTONDOWN => { const io = imgui.igGetIO(); if (event.button.button == 1) self.mouse_button_state[0] = true; if (event.button.button == 2) self.mouse_button_state[1] = true; if (event.button.button == 3) self.mouse_button_state[2] = true; return io.WantCaptureMouse; }, sdl.SDL_TEXTINPUT => { const io = imgui.igGetIO(); imgui.ImGuiIO_AddInputCharactersUTF8(io, &event.text.text[0]); return io.WantCaptureKeyboard; }, sdl.SDL_KEYDOWN, sdl.SDL_KEYUP => { const io = imgui.igGetIO(); const mod_state = @enumToInt(sdl.SDL_GetModState()); io.KeysDown[@intCast(usize, @enumToInt(event.key.keysym.scancode))] = event.type == sdl.SDL_KEYDOWN; io.KeyShift = (mod_state & @enumToInt(sdl.SDL_Keymod.KMOD_SHIFT)) != 0; io.KeyCtrl = (mod_state & @enumToInt(sdl.SDL_Keymod.KMOD_CTRL)) != 0; io.KeyAlt = (mod_state & @enumToInt(sdl.SDL_Keymod.KMOD_ALT)) != 0; if (@import("builtin").target.os.tag == .windows) io.KeySuper = false else io.KeySuper = (mod_state & @enumToInt(sdl.SDL_Keymod.KMOD_GUI)) != 0; return io.WantCaptureKeyboard; }, sdl.SDL_WINDOWEVENT => { // TODO: should this return true? const event_type = @intToEnum(sdl.SDL_WindowEventID, event.window.event); if (event_type == .SDL_WINDOWEVENT_CLOSE or event_type == .SDL_WINDOWEVENT_MOVED or event_type == .SDL_WINDOWEVENT_RESIZED) { if (imgui.igFindViewportByPlatformHandle(sdl.SDL_GetWindowFromID(event.window.windowID))) |viewport| { if (event_type == .SDL_WINDOWEVENT_CLOSE) viewport.PlatformRequestClose = true; if (event_type == .SDL_WINDOWEVENT_MOVED) viewport.PlatformRequestMove = true; if (event_type == .SDL_WINDOWEVENT_RESIZED) viewport.PlatformRequestResize = true; } } }, else => {}, } return false; } };
gamekit/imgui/events.zig
pub const PR = enum(i32) { SET_PDEATHSIG = 1, GET_PDEATHSIG = 2, GET_DUMPABLE = 3, SET_DUMPABLE = 4, GET_UNALIGN = 5, SET_UNALIGN = 6, GET_KEEPCAPS = 7, SET_KEEPCAPS = 8, GET_FPEMU = 9, SET_FPEMU = 10, GET_FPEXC = 11, SET_FPEXC = 12, GET_TIMING = 13, SET_TIMING = 14, SET_NAME = 15, GET_NAME = 16, GET_ENDIAN = 19, SET_ENDIAN = 20, GET_SECCOMP = 21, SET_SECCOMP = 22, CAPBSET_READ = 23, CAPBSET_DROP = 24, GET_TSC = 25, SET_TSC = 26, GET_SECUREBITS = 27, SET_SECUREBITS = 28, SET_TIMERSLACK = 29, GET_TIMERSLACK = 30, TASK_PERF_EVENTS_DISABLE = 31, TASK_PERF_EVENTS_ENABLE = 32, MCE_KILL = 33, MCE_KILL_GET = 34, SET_MM = 35, SET_PTRACER = 0x59616d61, SET_CHILD_SUBREAPER = 36, GET_CHILD_SUBREAPER = 37, SET_NO_NEW_PRIVS = 38, GET_NO_NEW_PRIVS = 39, GET_TID_ADDRESS = 40, SET_THP_DISABLE = 41, GET_THP_DISABLE = 42, MPX_ENABLE_MANAGEMENT = 43, MPX_DISABLE_MANAGEMENT = 44, SET_FP_MODE = 45, GET_FP_MODE = 46, CAP_AMBIENT = 47, SVE_SET_VL = 50, SVE_GET_VL = 51, GET_SPECULATION_CTRL = 52, SET_SPECULATION_CTRL = 53, _, }; pub const PR_SET_PDEATHSIG = @enumToInt(PR.SET_PDEATHSIG); pub const PR_GET_PDEATHSIG = @enumToInt(PR.GET_PDEATHSIG); pub const PR_GET_DUMPABLE = @enumToInt(PR.GET_DUMPABLE); pub const PR_SET_DUMPABLE = @enumToInt(PR.SET_DUMPABLE); pub const PR_GET_UNALIGN = @enumToInt(PR.GET_UNALIGN); pub const PR_SET_UNALIGN = @enumToInt(PR.SET_UNALIGN); pub const PR_UNALIGN_NOPRINT = 1; pub const PR_UNALIGN_SIGBUS = 2; pub const PR_GET_KEEPCAPS = @enumToInt(PR.GET_KEEPCAPS); pub const PR_SET_KEEPCAPS = @enumToInt(PR.SET_KEEPCAPS); pub const PR_GET_FPEMU = @enumToInt(PR.GET_FPEMU); pub const PR_SET_FPEMU = @enumToInt(PR.SET_FPEMU); pub const PR_FPEMU_NOPRINT = 1; pub const PR_FPEMU_SIGFPE = 2; pub const PR_GET_FPEXC = @enumToInt(PR.GET_FPEXC); pub const PR_SET_FPEXC = @enumToInt(PR.SET_FPEXC); pub const PR_FP_EXC_SW_ENABLE = 0x80; pub const PR_FP_EXC_DIV = 0x010000; pub const PR_FP_EXC_OVF = 0x020000; pub const PR_FP_EXC_UND = 0x040000; pub const PR_FP_EXC_RES = 0x080000; pub const PR_FP_EXC_INV = 0x100000; pub const PR_FP_EXC_DISABLED = 0; pub const PR_FP_EXC_NONRECOV = 1; pub const PR_FP_EXC_ASYNC = 2; pub const PR_FP_EXC_PRECISE = 3; pub const PR_GET_TIMING = @enumToInt(PR.GET_TIMING); pub const PR_SET_TIMING = @enumToInt(PR.SET_TIMING); pub const PR_TIMING_STATISTICAL = 0; pub const PR_TIMING_TIMESTAMP = 1; pub const PR_SET_NAME = @enumToInt(PR.SET_NAME); pub const PR_GET_NAME = @enumToInt(PR.GET_NAME); pub const PR_GET_ENDIAN = @enumToInt(PR.GET_ENDIAN); pub const PR_SET_ENDIAN = @enumToInt(PR.SET_ENDIAN); pub const PR_ENDIAN_BIG = 0; pub const PR_ENDIAN_LITTLE = 1; pub const PR_ENDIAN_PPC_LITTLE = 2; pub const PR_GET_SECCOMP = @enumToInt(PR.GET_SECCOMP); pub const PR_SET_SECCOMP = @enumToInt(PR.SET_SECCOMP); pub const PR_CAPBSET_READ = @enumToInt(PR.CAPBSET_READ); pub const PR_CAPBSET_DROP = @enumToInt(PR.CAPBSET_DROP); pub const PR_GET_TSC = @enumToInt(PR.GET_TSC); pub const PR_SET_TSC = @enumToInt(PR.SET_TSC); pub const PR_TSC_ENABLE = 1; pub const PR_TSC_SIGSEGV = 2; pub const PR_GET_SECUREBITS = @enumToInt(PR.GET_SECUREBITS); pub const PR_SET_SECUREBITS = @enumToInt(PR.SET_SECUREBITS); pub const PR_SET_TIMERSLACK = @enumToInt(PR.SET_TIMERSLACK); pub const PR_GET_TIMERSLACK = @enumToInt(PR.GET_TIMERSLACK); pub const PR_TASK_PERF_EVENTS_DISABLE = @enumToInt(PR.TASK_PERF_EVENTS_DISABLE); pub const PR_TASK_PERF_EVENTS_ENABLE = @enumToInt(PR.TASK_PERF_EVENTS_ENABLE); pub const PR_MCE_KILL = @enumToInt(PR.MCE_KILL); pub const PR_MCE_KILL_CLEAR = 0; pub const PR_MCE_KILL_SET = 1; pub const PR_MCE_KILL_LATE = 0; pub const PR_MCE_KILL_EARLY = 1; pub const PR_MCE_KILL_DEFAULT = 2; pub const PR_MCE_KILL_GET = @enumToInt(PR.MCE_KILL_GET); pub const PR_SET_MM = @enumToInt(PR.SET_MM); pub const PR_SET_MM_START_CODE = 1; pub const PR_SET_MM_END_CODE = 2; pub const PR_SET_MM_START_DATA = 3; pub const PR_SET_MM_END_DATA = 4; pub const PR_SET_MM_START_STACK = 5; pub const PR_SET_MM_START_BRK = 6; pub const PR_SET_MM_BRK = 7; pub const PR_SET_MM_ARG_START = 8; pub const PR_SET_MM_ARG_END = 9; pub const PR_SET_MM_ENV_START = 10; pub const PR_SET_MM_ENV_END = 11; pub const PR_SET_MM_AUXV = 12; pub const PR_SET_MM_EXE_FILE = 13; pub const PR_SET_MM_MAP = 14; pub const PR_SET_MM_MAP_SIZE = 15; pub const prctl_mm_map = extern struct { start_code: u64, end_code: u64, start_data: u64, end_data: u64, start_brk: u64, brk: u64, start_stack: u64, arg_start: u64, arg_end: u64, env_start: u64, env_end: u64, auxv: *u64, auxv_size: u32, exe_fd: u32, }; pub const PR_SET_PTRACER = @enumToInt(PR.SET_PTRACER); pub const PR_SET_PTRACER_ANY = std.math.maxInt(c_ulong); pub const PR_SET_CHILD_SUBREAPER = @enumToInt(PR.SET_CHILD_SUBREAPER); pub const PR_GET_CHILD_SUBREAPER = @enumToInt(PR.GET_CHILD_SUBREAPER); pub const PR_SET_NO_NEW_PRIVS = @enumToInt(PR.SET_NO_NEW_PRIVS); pub const PR_GET_NO_NEW_PRIVS = @enumToInt(PR.GET_NO_NEW_PRIVS); pub const PR_GET_TID_ADDRESS = @enumToInt(PR.GET_TID_ADDRESS); pub const PR_SET_THP_DISABLE = @enumToInt(PR.SET_THP_DISABLE); pub const PR_GET_THP_DISABLE = @enumToInt(PR.GET_THP_DISABLE); pub const PR_MPX_ENABLE_MANAGEMENT = @enumToInt(PR.MPX_ENABLE_MANAGEMENT); pub const PR_MPX_DISABLE_MANAGEMENT = @enumToInt(PR.MPX_DISABLE_MANAGEMENT); pub const PR_SET_FP_MODE = @enumToInt(PR.SET_FP_MODE); pub const PR_GET_FP_MODE = @enumToInt(PR.GET_FP_MODE); pub const PR_FP_MODE_FR = 1 << 0; pub const PR_FP_MODE_FRE = 1 << 1; pub const PR_CAP_AMBIENT = @enumToInt(PR.CAP_AMBIENT); pub const PR_CAP_AMBIENT_IS_SET = 1; pub const PR_CAP_AMBIENT_RAISE = 2; pub const PR_CAP_AMBIENT_LOWER = 3; pub const PR_CAP_AMBIENT_CLEAR_ALL = 4; pub const PR_SVE_SET_VL = @enumToInt(PR.SVE_SET_VL); pub const PR_SVE_SET_VL_ONEXEC = 1 << 18; pub const PR_SVE_GET_VL = @enumToInt(PR.SVE_GET_VL); pub const PR_SVE_VL_LEN_MASK = 0xffff; pub const PR_SVE_VL_INHERIT = 1 << 17; pub const PR_GET_SPECULATION_CTRL = @enumToInt(PR.GET_SPECULATION_CTRL); pub const PR_SET_SPECULATION_CTRL = @enumToInt(PR.SET_SPECULATION_CTRL); pub const PR_SPEC_STORE_BYPASS = 0; pub const PR_SPEC_NOT_AFFECTED = 0; pub const PR_SPEC_PRCTL = 1 << 0; pub const PR_SPEC_ENABLE = 1 << 1; pub const PR_SPEC_DISABLE = 1 << 2; pub const PR_SPEC_FORCE_DISABLE = 1 << 3;
lib/std/os/bits/linux/prctl.zig
pub const NotYetImplementedFn = extern fn(*@OpaqueType()) *@OpaqueType(); pub const Guid = extern struct { pub fn guid(data1: u32, data2: u16, data3: u16, data4: [8]u8) Guid { return Guid { .data1 = data1, .data2 = data2, .data3 = data3, .data4 = data4 }; } data1: u32, data2: u16, data3: u16, data4: [8]u8, }; pub const physical_addr = u64; pub const virtual_addr = u64; pub const Event = *@OpaqueType(); pub const ucs2 = u16; pub const Handle = *@OpaqueType(); pub const SystemTable = @import("tables/system_table.zig").SystemTable; pub const BootServices = @import("tables/boot_services.zig").BootServices; pub const RuntimeServices = @import("tables/runtime_services.zig").RuntimeServices; pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable; pub const protocols = @import("protocols.zig"); fn set_high_bit(comptime err_code: usize) usize { return err_code | (1 << @sizeOf(usize)); } pub const MemoryType = extern enum { ReservedMemoryType, LoaderCode, LoaderData, BootServicesCode, BootServicesData, RuntimeServicesCode, RuntimeServicesData, ConventionalMemory, UnusableMemory, ACPIReclaimMemory, ACPIMemoryNVS, MemoryMappedIO, MemoryMappedIOPortSpace, PalCode, PersistentMemory, MaxMemoryType, }; pub const MemoryAttribute = extern enum(u64) { Uc = 0x0000000000000001, Wc = 0x0000000000000002, Wt = 0x0000000000000004, Wb = 0x0000000000000008, Uce = 0x0000000000000010, Wp = 0x0000000000001000, Rp = 0x0000000000002000, Xp = 0x0000000000004000, Nv = 0x0000000000008000, MoreReliable = 0x0000000000010000, Ro = 0x0000000000020000, Runtime = 0x8000000000000000, }; pub const MemoryDescriptor = extern struct { type: MemoryType, physical_start: physical_addr, virtual_start: virtual_addr, number_of_pages: u64, attribute: MemoryAttribute, }; pub const Status = usize; pub const StatusValues = enum(Status) { Success = 0, LoadError = set_high_bit(1), InvalidParameter = set_high_bit(2), Unsupported = set_high_bit(3), BadBufferSize = set_high_bit(4), BufferTooSmall = set_high_bit(5), NotReady = set_high_bit(6), DeviceError = set_high_bit(7), WriteProtected = set_high_bit(8), OutOfResources = set_high_bit(9), VolumeCorrupted = set_high_bit(10), VolumeFull = set_high_bit(11), NoMedia = set_high_bit(12), MediaChanged = set_high_bit(13), NotFound = set_high_bit(14), AccessDenied = set_high_bit(15), NoResponse = set_high_bit(16), NoMapping = set_high_bit(17), Timeout = set_high_bit(18), NotStarted = set_high_bit(19), AlreadyStarted = set_high_bit(20), Aborted = set_high_bit(21), IcmpError = set_high_bit(22), TftpError = set_high_bit(23), ProtocolError = set_high_bit(24), IncompatibleVersion = set_high_bit(25), SecurityViolation = set_high_bit(26), CrcError = set_high_bit(27), EndOfMedia = set_high_bit(28), EndOfFile = set_high_bit(31), InvalidLanguage = set_high_bit(32), CompromisedData = set_high_bit(33), IpAddressConflict = set_high_bit(34), HttpError = set_high_bit(35), };
src/uefi/uefi.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const int = i64; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day20.txt"); const Image = struct { key: *const [512]u8, grid: []u8, start: usize, pitch: usize, width: usize, height: usize, default: u8 = '.', pub fn deinit(self: *@This()) void { gpa.free(self.grid); self.* = undefined; } pub fn enhance(self: *@This()) void { // Figure out the next default self.default = if (self.default == '.') self.key[0] else self.key[0b111_111_111]; // Allocate a one larger grid with a border const new_width = self.width + 2; const new_height = self.height + 2; const new_pitch = new_width + 2; const new_start = new_pitch + 1; const new_grid = gpa.alloc(u8, @intCast(usize, new_pitch * (new_height + 2))) catch unreachable; // Set the new border to the default { @memset(new_grid.ptr, self.default, new_pitch * 2); @memset(new_grid.ptr + new_grid.len - 2 * new_pitch, self.default, 2 * new_pitch); var y: usize = 0; while (y < new_height) : (y += 1) { const base = (y+1) * new_pitch + new_start; new_grid[base - 1] = self.default; new_grid[base] = self.default; new_grid[base + new_width - 1] = self.default; new_grid[base + new_width] = self.default; } } // Update image var y: usize = 0; while (y < self.height) : (y += 1) { var x: usize = 0; while (x < self.width) : (x += 1) { const in_center = y * self.pitch + x + self.start; const out_center = (y + 1) * new_pitch + (x + 1) + new_start; var lookup_id: u32 = 0; if (self.grid[in_center - self.pitch - 1] == '#') lookup_id |= (1<<8); if (self.grid[in_center - self.pitch ] == '#') lookup_id |= (1<<7); if (self.grid[in_center - self.pitch + 1] == '#') lookup_id |= (1<<6); if (self.grid[in_center - 1] == '#') lookup_id |= (1<<5); if (self.grid[in_center ] == '#') lookup_id |= (1<<4); if (self.grid[in_center + 1] == '#') lookup_id |= (1<<3); if (self.grid[in_center + self.pitch - 1] == '#') lookup_id |= (1<<2); if (self.grid[in_center + self.pitch ] == '#') lookup_id |= (1<<1); if (self.grid[in_center + self.pitch + 1] == '#') lookup_id |= (1<<0); new_grid[out_center] = self.key[lookup_id]; } } // Persist results gpa.free(self.grid); self.grid = new_grid; self.width = new_width; self.height = new_height; self.start = new_start; self.pitch = new_pitch; } pub fn countLit(self: @This()) usize { assert(self.default == '.'); var total: usize = 0; for (self.grid) |c| { if (c == '#') total += 1; } return total; } }; pub fn main() !void { var timer = try std.time.Timer.start(); var grid = blk: { var width: usize = 0; var height: usize = 0; var height_map = List(u8).init(gpa); errdefer height_map.deinit(); var lines = tokenize(u8, data, "\r\n"); const key = lines.next().?[0..512]; while (lines.next()) |line| { if (line.len == 0) { continue; } if (width == 0) { width = line.len; try height_map.appendNTimes('.', (width + 4) * 2); } else { assert(width == line.len); } try height_map.appendNTimes('.', 2); for (line) |c| { try height_map.append(c); } height += 1; try height_map.appendNTimes('.', 2); } try height_map.appendNTimes('.', (width + 4) * 2); break :blk Image{ .key = key, .grid = height_map.toOwnedSlice(), .width = width + 2, .height = height + 2, .pitch = width + 4, .start = width + 5, }; }; defer grid.deinit(); const parse_time = timer.lap(); var i: usize = 0; while (i < 2) : (i += 1) { grid.enhance(); } const part1 = grid.countLit(); const part1_time = timer.lap(); while (i < 50) : (i += 1) { grid.enhance(); } const part2 = grid.countLit(); const part2_time = timer.lap(); print("part1={}, part2={}\n", .{part1, part2}); print("Timing: parse={}, part1={}, part2={}, total={}\n", .{parse_time, part1_time, part2_time, parse_time + part1_time + part2_time}); } fn printGrid(grid: []const u8, pitch: usize) void { var i: usize = 0; while (i < grid.len) : (i += pitch) { print("{s}\n", .{grid[i..][0..pitch]}); } print("\n", .{}); assert(i == grid.len); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const eql = std.mem.eql; const parseEnum = std.meta.stringToEnum; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day20.zig
const std = @import("std"); const string = []const u8; const range = @import("range").range; const extras = @import("extras"); const time = @This(); pub const DateTime = struct { ms: u16, seconds: u16, minutes: u16, hours: u16, days: u16, months: u16, years: u16, timezone: TimeZone, weekday: WeekDay, era: Era, const Self = @This(); pub fn initUnixMs(unix: u64) Self { return epoch_unix.addMs(unix); } pub fn initUnix(unix: u64) Self { return epoch_unix.addSecs(unix); } /// Caller asserts that this is > epoch pub fn init(year: u16, month: u16, day: u16, hr: u16, min: u16, sec: u16) Self { return epoch_unix .addYears(year - epoch_unix.years) .addMonths(month) .addDays(day) .addHours(hr) .addMins(min) .addSecs(sec); } pub fn now() Self { return initUnixMs(@intCast(u64, std.time.milliTimestamp())); } pub const epoch_unix = Self{ .ms = 0, .seconds = 0, .minutes = 0, .hours = 0, .days = 0, .months = 0, .years = 1970, .timezone = .UTC, .weekday = .Thu, .era = .AD, }; pub fn eql(self: Self, other: Self) bool { return self.ms == other.ms and self.seconds == other.seconds and self.minutes == other.minutes and self.hours == other.hours and self.days == other.days and self.months == other.months and self.years == other.years and self.timezone == other.timezone and self.weekday == other.weekday; } pub fn addMs(self: Self, count: u64) Self { if (count == 0) return self; var result = self; result.ms += @intCast(u16, count % 1000); return result.addSecs(count / 1000); } pub fn addSecs(self: Self, count: u64) Self { if (count == 0) return self; var result = self; result.seconds += @intCast(u16, count % 60); return result.addMins(count / 60); } pub fn addMins(self: Self, count: u64) Self { if (count == 0) return self; var result = self; result.minutes += @intCast(u16, count % 60); return result.addHours(count / 60); } pub fn addHours(self: Self, count: u64) Self { if (count == 0) return self; var result = self; result.hours += @intCast(u16, count % 24); return result.addDays(count / 24); } pub fn addDays(self: Self, count: u64) Self { if (count == 0) return self; var result = self; var input = count; while (true) { const year_len = result.daysThisYear(); if (input >= year_len) { result.years += 1; input -= year_len; result.incrementWeekday(year_len); continue; } break; } while (true) { const month_len = result.daysThisMonth(); if (input >= month_len) { result.months += 1; input -= month_len; result.incrementWeekday(month_len); if (result.months == 12) { result.years += 1; result.months = 0; } continue; } break; } { const month_len = result.daysThisMonth(); if (result.days + input > month_len) { const left = month_len - result.days; input -= left; result.months += 1; result.days = 0; result.incrementWeekday(left); } result.days += @intCast(u16, input); result.incrementWeekday(input); if (result.months == 12) { result.years += 1; result.months = 0; } } return result; } pub fn addMonths(self: Self, count: u64) Self { if (count == 0) return self; var result = self; var input = count; while (input > 0) { const new = result.addDays(result.daysThisMonth()); result = new; input -= 1; } return result; } pub fn addYears(self: Self, count: u64) Self { if (count == 0) return self; return self.addMonths(count * 12); } pub fn isLeapYear(self: Self) bool { return time.isLeapYear(self.years); } pub fn daysThisYear(self: Self) u16 { return time.daysInYear(self.years); } pub fn daysThisMonth(self: Self) u16 { return self.daysInMonth(self.months); } fn daysInMonth(self: Self, month: u16) u16 { return time.daysInMonth(self.years, month); } fn incrementWeekday(self: *Self, count: u64) void { var i = count % 7; while (i > 0) : (i -= 1) { self.weekday = self.weekday.next(); } } pub fn dayOfThisYear(self: Self) u16 { var ret: u16 = 0; for (range(self.months)) |_, item| { ret += self.daysInMonth(@intCast(u16, item)); } ret += self.days; return ret; } // pub fn toUnix(self: Self) u64 { // const x = self.toUnix(); // return x / 1000; // } pub fn toUnixMilli(self: Self) u64 { var res: u64 = 0; res += self.ms; res += @as(u64, self.seconds) * std.time.ms_per_s; res += @as(u64, self.minutes) * std.time.ms_per_min; res += @as(u64, self.hours) * std.time.ms_per_hour; res += self.daysSinceEpoch() * std.time.ms_per_day; return res; } fn daysSinceEpoch(self: Self) u64 { var res: u64 = 0; res += self.days; for (range(self.years - epoch_unix.years)) |_, i| res += time.daysInYear(@intCast(u16, i)); for (range(self.months)) |_, i| res += self.daysInMonth(@intCast(u16, i)); return res; } /// fmt is based on https://momentjs.com/docs/#/displaying/format/ pub fn format(self: Self, comptime fmt: string, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; if (fmt.len == 0) @compileError("DateTime: format string can't be empty"); _ = writer; _ = self; @setEvalBranchQuota(100000); comptime var s = 0; comptime var e = 0; comptime var next: ?FormatSeq = null; inline for (fmt) |c, i| { e = i + 1; if (comptime std.meta.stringToEnum(FormatSeq, fmt[s..e])) |tag| { next = tag; if (i < fmt.len - 1) continue; } if (next) |tag| { switch (tag) { .MM => try writer.print("{:0>2}", .{self.months + 1}), .M => try writer.print("{}", .{self.months + 1}), .Mo => try printOrdinal(writer, self.months + 1), .MMM => try printLongName(writer, self.months, &[_]string{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }), .MMMM => try printLongName(writer, self.months, &[_]string{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }), .Q => try writer.print("{}", .{self.months / 3 + 1}), .Qo => try printOrdinal(writer, self.months / 3 + 1), .D => try writer.print("{}", .{self.days + 1}), .Do => try printOrdinal(writer, self.days + 1), .DD => try writer.print("{:0>2}", .{self.days + 1}), .DDD => try writer.print("{}", .{self.dayOfThisYear() + 1}), .DDDo => try printOrdinal(writer, self.dayOfThisYear() + 1), .DDDD => try writer.print("{:0>3}", .{self.dayOfThisYear() + 1}), .d => try writer.print("{}", .{@enumToInt(self.weekday)}), .do => try printOrdinal(writer, @enumToInt(self.weekday)), .dd => try writer.writeAll(@tagName(self.weekday)[0..2]), .ddd => try writer.writeAll(@tagName(self.weekday)), .dddd => try printLongName(writer, @enumToInt(self.weekday), &[_]string{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }), .e => try writer.print("{}", .{@enumToInt(self.weekday)}), .E => try writer.print("{}", .{@enumToInt(self.weekday) + 1}), .w => try writer.print("{}", .{self.dayOfThisYear() / 7 + 1}), .wo => try printOrdinal(writer, self.dayOfThisYear() / 7 + 1), .ww => try writer.print("{:0>2}", .{self.dayOfThisYear() / 7 + 1}), .Y => try writer.print("{}", .{self.years + 10000}), .YY => try writer.print("{:0>2}", .{self.years % 100}), .YYY => try writer.print("{}", .{self.years}), .YYYY => try writer.print("{:0>4}", .{self.years}), .N => try writer.writeAll(@tagName(self.era)), .NN => try writer.writeAll("Anno Domini"), .A => try printLongName(writer, self.hours / 12, &[_]string{ "AM", "PM" }), .a => try printLongName(writer, self.hours / 12, &[_]string{ "am", "pm" }), .H => try writer.print("{}", .{self.hours}), .HH => try writer.print("{:0>2}", .{self.hours}), .h => try writer.print("{}", .{wrap(self.hours, 12)}), .hh => try writer.print("{:0>2}", .{wrap(self.hours, 12)}), .k => try writer.print("{}", .{wrap(self.hours, 24)}), .kk => try writer.print("{:0>2}", .{wrap(self.hours, 24)}), .m => try writer.print("{}", .{self.minutes}), .mm => try writer.print("{:0>2}", .{self.minutes}), .s => try writer.print("{}", .{self.seconds}), .ss => try writer.print("{:0>2}", .{self.seconds}), .S => try writer.print("{}", .{self.ms / 100}), .SS => try writer.print("{:0>2}", .{self.ms / 10}), .SSS => try writer.print("{:0>3}", .{self.ms}), .z => try writer.writeAll(@tagName(self.timezone)), .Z => try writer.writeAll("+00:00"), .ZZ => try writer.writeAll("+0000"), .x => try writer.print("{}", .{self.toUnixMilli()}), // .X => try writer.print("{}", .{self.toUnix()}), } next = null; s = i; } switch (c) { ',', ' ', ':', '-', '.', 'T', 'W', => { try writer.writeAll(&.{c}); s = i + 1; continue; }, else => {}, } if (i < fmt.len - 1) @compileError(comptime std.fmt.comptimePrint("'{s}' is not a valid format sequence", .{fmt[s..e]})); } } pub fn formatAlloc(self: Self, alloc: std.mem.Allocator, comptime fmt: string) !string { var list = std.ArrayList(u8).init(alloc); defer list.deinit(); try self.format(fmt, .{}, list.writer()); return list.toOwnedSlice(); } const FormatSeq = enum { M, // 1 2 ... 11 12 Mo, // 1st 2nd ... 11th 12th MM, // 01 02 ... 11 12 MMM, // Jan Feb ... Nov Dec MMMM, // January February ... November December Q, // 1 2 3 4 Qo, // 1st 2nd 3rd 4th D, // 1 2 ... 30 31 Do, // 1st 2nd ... 30th 31st DD, // 01 02 ... 30 31 DDD, // 1 2 ... 364 365 DDDo, // 1st 2nd ... 364th 365th DDDD, // 001 002 ... 364 365 d, // 0 1 ... 5 6 do, // 0th 1st ... 5th 6th dd, // Su Mo ... Fr Sa ddd, // Sun Mon ... Fri Sat dddd, // Sunday Monday ... Friday Saturday e, // 0 1 ... 5 6 (locale) E, // 1 2 ... 6 7 (ISO) w, // 1 2 ... 52 53 wo, // 1st 2nd ... 52nd 53rd ww, // 01 02 ... 52 53 Y, // 11970 11971 ... 19999 20000 20001 (Holocene calendar) YY, // 70 71 ... 29 30 YYY, // 1 2 ... 1970 1971 ... 2029 2030 YYYY, // 0001 0002 ... 1970 1971 ... 2029 2030 N, // BC AD NN, // Before Christ ... Anno Domini A, // AM PM a, // am pm H, // 0 1 ... 22 23 HH, // 00 01 ... 22 23 h, // 1 2 ... 11 12 hh, // 01 02 ... 11 12 k, // 1 2 ... 23 24 kk, // 01 02 ... 23 24 m, // 0 1 ... 58 59 mm, // 00 01 ... 58 59 s, // 0 1 ... 58 59 ss, // 00 01 ... 58 59 S, // 0 1 ... 8 9 (second fraction) SS, // 00 01 ... 98 99 SSS, // 000 001 ... 998 999 z, // EST CST ... MST PST Z, // -07:00 -06:00 ... +06:00 +07:00 ZZ, // -0700 -0600 ... +0600 +0700 x, // unix milli // X, // unix }; }; pub const format = struct { pub const LT = ""; pub const LTS = ""; pub const L = ""; pub const l = ""; pub const LL = ""; pub const ll = ""; pub const LLL = ""; pub const lll = ""; pub const LLLL = ""; pub const llll = ""; }; pub const TimeZone = enum { UTC, usingnamespace extras.TagNameJsonStringifyMixin(@This()); }; pub const WeekDay = enum { Sun, Mon, Tue, Wed, Thu, Fri, Sat, pub fn next(self: WeekDay) WeekDay { return switch (self) { .Sun => .Mon, .Mon => .Tue, .Tue => .Wed, .Wed => .Thu, .Thu => .Fri, .Fri => .Sat, .Sat => .Sun, }; } usingnamespace extras.TagNameJsonStringifyMixin(@This()); }; pub const Era = enum { // BC, AD, usingnamespace extras.TagNameJsonStringifyMixin(@This()); }; pub fn isLeapYear(year: u16) bool { var ret = false; if (year % 4 == 0) ret = true; if (year % 100 == 0) ret = false; if (year % 400 == 0) ret = true; return ret; } pub fn daysInYear(year: u16) u16 { return if (isLeapYear(year)) 366 else 365; } fn daysInMonth(year: u16, month: u16) u16 { const norm = [12]u16{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; const leap = [12]u16{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; const month_days = if (!isLeapYear(year)) norm else leap; return month_days[month]; } fn printOrdinal(writer: anytype, num: u16) !void { try writer.print("{}", .{num}); try writer.writeAll(switch (num) { 1 => "st", 2 => "nd", 3 => "rd", else => "th", }); } fn printLongName(writer: anytype, index: u16, names: []const string) !void { try writer.writeAll(names[index]); } fn wrap(val: u16, at: u16) !u16 { var tmp = val % at; return if (tmp == 0) at else tmp; }
time.zig
const std = @import("std"); const interop = @import("../interop.zig"); const iup = @import("../iup.zig"); const Impl = @import("../impl.zig").Impl; const CallbackHandler = @import("../callback_handler.zig").CallbackHandler; const debug = std.debug; const trait = std.meta.trait; const Element = iup.Element; const Handle = iup.Handle; const Error = iup.Error; const ChildrenIterator = iup.ChildrenIterator; const Size = iup.Size; const Margin = iup.Margin; /// /// Creates a native container for composing elements in hidden layers with /// only one layer visible (just like IupZbox), but its visibility can be /// interactively controlled. /// The interaction is done in a line of tabs with titles and arranged /// according to the tab type. /// Also known as Notebook in native systems. pub const Tabs = opaque { pub const CLASS_NAME = "tabs"; pub const NATIVE_TYPE = iup.NativeType.Control; const Self = @This(); /// /// FOCUS_CB: Called when a child of the container gets or looses the focus. /// It is called only if PROPAGATEFOCUS is defined in the child. /// (since 3.23) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus: /// number) -> (ret: number) [in Lua] pub const OnFocusFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// TABCHANGE_CB: Callback called when the user changes the current tab. /// It is not called when the current tab is programmatically changed or removed. /// int function(Ihandle* ih, Ihandle* new_tab, Ihandle* old_tab); [in C] /// ih:tabchange_cb(new_tab, old_tab: ihandle) -> (ret: number) [in Lua] pub const OnTabChangeFn = fn (self: *Self, arg0: iup.Element, arg1: iup.Element) anyerror!void; /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub const OnKAnyFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub const OnHelpFn = fn (self: *Self) anyerror!void; /// /// RIGHTCLICK_CB: Callback called when the user clicks on some tab using the /// right mouse button (since 3.10). /// int function(Ihandle* ih, int pos); [in C] ih:rightclick_cb(pos: number) -> /// (ret: number) [in Lua] pub const OnRightClickFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnMapFn = fn (self: *Self) anyerror!void; /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub const OnEnterWindowFn = fn (self: *Self) anyerror!void; /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub const OnDestroyFn = fn (self: *Self) anyerror!void; /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub const OnKillFocusFn = fn (self: *Self) anyerror!void; /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnUnmapFn = fn (self: *Self) anyerror!void; /// /// TABCHANGEPOS_CB: Callback called when the user changes the current tab. /// Called only when TABCHANGE_CB is not defined. /// (since 3.3) int function(Ihandle* ih, int new_pos, int old_pos); [in C] /// ih:tabchange_cb(new_pos, old_pos: number) -> (ret: number) [in Lua] pub const OnTabChangePosFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void; /// /// TABCLOSE_CB [Windows and GTK Only]: Callback called when the user clicks on /// the close button (since 3.10). /// Called only when SHOWCLOSE=Yes. /// int function(Ihandle* ih, int pos); [in C] ih:tabclose_cb(pos: number) -> /// (ret: number) [in Lua] pub const OnTabCloseFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub const OnGetFocusFn = fn (self: *Self) anyerror!void; pub const OnLDestroyFn = fn (self: *Self) anyerror!void; /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub const OnLeaveWindowFn = fn (self: *Self) anyerror!void; pub const OnPostMessageFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: f64, arg3: *iup.Unknow) anyerror!void; pub const ZOrder = enum { Top, Bottom, }; /// /// TABTYPE (non inheritable) (creation only in Windows): Indicates the type of /// tab, which can be "TOP", "BOTTOM", "LEFT" or "RIGHT". /// Default is "TOP". /// In Windows, if LEFT or RIGHT then MULTILINE=YES and TABORIENTATION=VERTICAL /// are set, if TOP or BOTTOM then TABORIENTATION=HORIZONTAL is set. /// In Windows, when not TOP, then visual style is removed from tabs. /// In Windows, the Visual Styles work only when TABTYPE is TOP. /// Windows Classic Windows w/ Styles pub const TabType = enum { Bottom, Left, Right, Top, }; /// /// EXPAND (non inheritable): The default value is "YES". pub const Expand = enum { Yes, Horizontal, Vertical, HorizontalFree, VerticalFree, No, }; /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.27) pub const Floating = enum { Yes, Ignore, No, }; /// /// TABORIENTATION (non inheritable): Indicates the orientation of tab text, /// which can be "HORIZONTAL" or "VERTICAL". /// Default is "HORIZONTAL". /// VERTICAL is supported only in GTK and in Windows. /// In Windows, it can NOT be set, it is dependent on the TABTYPE attribute, if /// TABTYPE=LEFT or TABTYPE=RIGHT then TABORIENTATION=VERTICAL, if TABTYPE=TOP /// or TABTYPE=BOTTOM then TABORIENTATION=HORIZONTAL. /// (GTK 2.6) pub const TabOrientation = enum { Horizontal, Vertical, }; pub const Initializer = struct { last_error: ?anyerror = null, ref: *Self, /// /// Returns a pointer to IUP element or an error. /// Only top-level or detached elements needs to be unwraped, pub fn unwrap(self: Initializer) !*Self { if (self.last_error) |e| { return e; } else { return self.ref; } } /// /// Captures a reference into a external variable /// Allows to capture some references even using full declarative API pub fn capture(self: *Initializer, ref: **Self) Initializer { ref.* = self.ref; return self.*; } pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; Self.setStrAttribute(self.ref, attributeName, arg); return self.*; } pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer { if (self.last_error) |_| return self.*; Self.setIntAttribute(self.ref, attributeName, arg); return self.*; } pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer { if (self.last_error) |_| return self.*; Self.setBoolAttribute(self.ref, attributeName, arg); return self.*; } pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer { if (self.last_error) |_| return self.*; Self.setPtrAttribute(self.ref, T, attributeName, value); return self.*; } pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setHandle(self.ref, arg); return self.*; } pub fn setChildren(self: *Initializer, tuple: anytype) Initializer { if (self.last_error) |_| return self.*; Self.appendChildren(self.ref, tuple) catch |err| { self.last_error = err; }; return self.*; } /// /// FGCOLOR: Tabs title color. /// Default: the global attribute DLGFGCOLOR. pub fn setFgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "FGCOLOR", .{}, rgb); return self.*; } pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg); return self.*; } pub fn setTipBgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "TIPBGCOLOR", .{}, rgb); return self.*; } pub fn setTipIcon(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIPICON", .{}, arg); return self.*; } pub fn setMaxSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value); return self.*; } pub fn setPosition(self: *Initializer, x: i32, y: i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self.ref, "POSITION", .{}, value); return self.*; } pub fn setTip(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIP", .{}, arg); return self.*; } /// /// SHOWCLOSE [Windows and GTK Only] (non inheritable): enables the close /// button on each tab. /// Default value: "NO". /// In Windows the close button imply the classic visual for the control. /// By default when closed the tab is hidden. /// To change that behavior use the TABCLOSE_CB callback. /// (since 3.10) pub fn setShowClose(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "SHOWCLOSE", .{}, arg); return self.*; } pub fn setCanFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg); return self.*; } pub fn setVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg); return self.*; } pub fn zOrder(self: *Initializer, arg: ?ZOrder) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self.ref, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self.ref, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self.ref, "ZORDER", .{}); } return self.*; } pub fn setTheme(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "THEME", .{}, arg); return self.*; } /// /// CHILDOFFSET: Allow to specify a position offset for the child. /// Available for native containers only. /// It will not affect the natural size, and allows to position controls /// outside the client area. /// Format "dxxdy", where dx and dy are integer values corresponding to the /// horizontal and vertical offsets, respectively, in pixels. /// Default: 0x0. /// (since 3.14) pub fn setChildOffset(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "CHILDOFFSET", .{}, value); return self.*; } /// /// TABTYPE (non inheritable) (creation only in Windows): Indicates the type of /// tab, which can be "TOP", "BOTTOM", "LEFT" or "RIGHT". /// Default is "TOP". /// In Windows, if LEFT or RIGHT then MULTILINE=YES and TABORIENTATION=VERTICAL /// are set, if TOP or BOTTOM then TABORIENTATION=HORIZONTAL is set. /// In Windows, when not TOP, then visual style is removed from tabs. /// In Windows, the Visual Styles work only when TABTYPE is TOP. /// Windows Classic Windows w/ Styles pub fn setTabType(self: *Initializer, arg: ?TabType) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Bottom => interop.setStrAttribute(self.ref, "TABTYPE", .{}, "BOTTOM"), .Left => interop.setStrAttribute(self.ref, "TABTYPE", .{}, "LEFT"), .Right => interop.setStrAttribute(self.ref, "TABTYPE", .{}, "RIGHT"), .Top => interop.setStrAttribute(self.ref, "TABTYPE", .{}, "TOP"), } else { interop.clearAttribute(self.ref, "TABTYPE", .{}); } return self.*; } /// /// EXPAND (non inheritable): The default value is "YES". pub fn setExpand(self: *Initializer, arg: ?Expand) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self.ref, "EXPAND", .{}); } return self.*; } /// /// SIZE (non inheritable): The default size is the smallest size that fits its /// largest child. /// All child elements are considered even invisible ones. pub fn setSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "SIZE", .{}, value); return self.*; } pub fn setTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TIPMARKUP", .{}, arg); return self.*; } pub fn setFontSize(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg); return self.*; } pub fn setUserSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "USERSIZE", .{}, value); return self.*; } pub fn setTipDelay(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg); return self.*; } /// /// TABVISIBLEn (non inheritable): Allows to hide a tab. /// n starts at 0. /// When a tab is hidden the tabs indices are not changed. /// Can be Yes or No. /// Default: Yes. /// (since 3.8) pub fn setTabVisible(self: *Initializer, index: i32, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TABVISIBLE", .{index}, arg); return self.*; } pub fn setPropagateFocus(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg); return self.*; } /// /// BGCOLOR: In Windows and in GTK when in Windows, the tab buttons background /// it will be always defined by the system. /// In Windows the default background is different from the dialog background. /// Default: the global attribute DLGBGCOLOR. pub fn setBgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "BGCOLOR", .{}, rgb); return self.*; } /// /// VALUE_HANDLE (non inheritable): Changes the current tab by its handle. /// The value passed must be the handle of a child contained in the tabs. /// When the tabs is created, the first element inserted is set as the visible child. /// (since 3.0) pub fn setValueHandle(self: *Initializer, arg: anytype) !Initializer { if (self.last_error) |_| return self.*; interop.setHandleAttribute(self.ref, "VALUE_HANDLE", .{}, arg); return self.*; } pub fn setValueHandleHandleName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "VALUE_HANDLE", .{}, arg); return self.*; } /// /// CHILDSIZEALL (non inheritable): compute the natural size using all children. /// If set to NO will compute using only the current tab. /// Default: Yes. /// (since 3.27) pub fn setChildSizeAll(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "CHILDSIZEALL", .{}, arg); return self.*; } /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.27) pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self.ref, "FLOATING", .{}); } return self.*; } pub fn setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg); return self.*; } pub fn setRasterSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value); return self.*; } pub fn setTipFgColor(self: *Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self.*; interop.setRgb(self.ref, "TIPFGCOLOR", .{}, rgb); return self.*; } pub fn setFontFace(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg); return self.*; } /// /// TABORIENTATION (non inheritable): Indicates the orientation of tab text, /// which can be "HORIZONTAL" or "VERTICAL". /// Default is "HORIZONTAL". /// VERTICAL is supported only in GTK and in Windows. /// In Windows, it can NOT be set, it is dependent on the TABTYPE attribute, if /// TABTYPE=LEFT or TABTYPE=RIGHT then TABORIENTATION=VERTICAL, if TABTYPE=TOP /// or TABTYPE=BOTTOM then TABORIENTATION=HORIZONTAL. /// (GTK 2.6) pub fn setTabOrientation(self: *Initializer, arg: ?TabOrientation) Initializer { if (self.last_error) |_| return self.*; if (arg) |value| switch (value) { .Horizontal => interop.setStrAttribute(self.ref, "TABORIENTATION", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self.ref, "TABORIENTATION", .{}, "VERTICAL"), } else { interop.clearAttribute(self.ref, "TABORIENTATION", .{}); } return self.*; } pub fn setName(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NAME", .{}, arg); return self.*; } /// /// VALUEPOS (non inheritable): Changes the current tab by its position, /// starting at 0. /// When the tabs is created, the first element inserted is set as the visible child. /// In GTK, inside the callback the returned value is still the previous one. /// (since 3.0) pub fn setValuePos(self: *Initializer, arg: i32) Initializer { if (self.last_error) |_| return self.*; interop.setIntAttribute(self.ref, "VALUEPOS", .{}, arg); return self.*; } /// /// VALUE (non inheritable): Changes the current tab by its name. /// The value passed must be the name of one of the elements contained in the tabs. /// Use IupSetHandle or IupSetAttributeHandle to associate a child to a name. /// In Lua you can also use the element reference directly. pub fn setValue(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "VALUE", .{}, arg); return self.*; } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer { if (self.last_error) |_| return self.*; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg); } else |err| { self.last_error = err; } return self.*; } pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg); return self.*; } /// /// MULTILINE [Windows Only] (non inheritable): Enable multiple lines of tab buttons. /// This will hide the tab scroll and fits to make all tab buttons visible. /// Can be "YES" or "NO". /// Default "NO". /// It is always enabled when TABTYPE=LEFT or TABTYPE=RIGHT. /// (since 3.0) pub fn setMultiline(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "MULTILINE", .{}, arg); return self.*; } /// /// ACTIVE, FONT, SCREENPOSITION, POSITION, CLIENTSIZE, CLIENTOFFSET, MINSIZE, /// MAXSIZE, WID, TIP, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn setActive(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg); return self.*; } pub fn setTipVisible(self: *Initializer, arg: bool) Initializer { if (self.last_error) |_| return self.*; interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg); return self.*; } pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer { if (self.last_error) |_| return self.*; interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg); return self.*; } pub fn setMinSize(self: *Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self.*; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MINSIZE", .{}, value); return self.*; } pub fn setNTheme(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "NTHEME", .{}, arg); return self.*; } pub fn setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg); return self.*; } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg); return self.*; } pub fn setFont(self: *Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self.*; interop.setStrAttribute(self.ref, "FONT", .{}, arg); return self.*; } /// /// FOCUS_CB: Called when a child of the container gets or looses the focus. /// It is called only if PROPAGATEFOCUS is defined in the child. /// (since 3.23) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus: /// number) -> (ret: number) [in Lua] pub fn setFocusCallback(self: *Initializer, callback: ?OnFocusFn) Initializer { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// TABCHANGE_CB: Callback called when the user changes the current tab. /// It is not called when the current tab is programmatically changed or removed. /// int function(Ihandle* ih, Ihandle* new_tab, Ihandle* old_tab); [in C] /// ih:tabchange_cb(new_tab, old_tab: ihandle) -> (ret: number) [in Lua] pub fn setTabChangeCallback(self: *Initializer, callback: ?OnTabChangeFn) Initializer { const Handler = CallbackHandler(Self, OnTabChangeFn, "TABCHANGE_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub fn setKAnyCallback(self: *Initializer, callback: ?OnKAnyFn) Initializer { const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY"); Handler.setCallback(self.ref, callback); return self.*; } /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub fn setHelpCallback(self: *Initializer, callback: ?OnHelpFn) Initializer { const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// RIGHTCLICK_CB: Callback called when the user clicks on some tab using the /// right mouse button (since 3.10). /// int function(Ihandle* ih, int pos); [in C] ih:rightclick_cb(pos: number) -> /// (ret: number) [in Lua] pub fn setRightClickCallback(self: *Initializer, callback: ?OnRightClickFn) Initializer { const Handler = CallbackHandler(Self, OnRightClickFn, "RIGHTCLICK_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: *Initializer, callback: ?OnMapFn) Initializer { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: *Initializer, callback: ?OnEnterWindowFn) Initializer { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub fn setDestroyCallback(self: *Initializer, callback: ?OnDestroyFn) Initializer { const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub fn setKillFocusCallback(self: *Initializer, callback: ?OnKillFocusFn) Initializer { const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: *Initializer, callback: ?OnUnmapFn) Initializer { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// TABCHANGEPOS_CB: Callback called when the user changes the current tab. /// Called only when TABCHANGE_CB is not defined. /// (since 3.3) int function(Ihandle* ih, int new_pos, int old_pos); [in C] /// ih:tabchange_cb(new_pos, old_pos: number) -> (ret: number) [in Lua] pub fn setTabChangePosCallback(self: *Initializer, callback: ?OnTabChangePosFn) Initializer { const Handler = CallbackHandler(Self, OnTabChangePosFn, "TABCHANGEPOS_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// TABCLOSE_CB [Windows and GTK Only]: Callback called when the user clicks on /// the close button (since 3.10). /// Called only when SHOWCLOSE=Yes. /// int function(Ihandle* ih, int pos); [in C] ih:tabclose_cb(pos: number) -> /// (ret: number) [in Lua] pub fn setTabCloseCallback(self: *Initializer, callback: ?OnTabCloseFn) Initializer { const Handler = CallbackHandler(Self, OnTabCloseFn, "TABCLOSE_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub fn setGetFocusCallback(self: *Initializer, callback: ?OnGetFocusFn) Initializer { const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setLDestroyCallback(self: *Initializer, callback: ?OnLDestroyFn) Initializer { const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB"); Handler.setCallback(self.ref, callback); return self.*; } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: *Initializer, callback: ?OnLeaveWindowFn) Initializer { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self.ref, callback); return self.*; } pub fn setPostMessageCallback(self: *Initializer, callback: ?OnPostMessageFn) Initializer { const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB"); Handler.setCallback(self.ref, callback); return self.*; } }; pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void { interop.setStrAttribute(self, attribute, .{}, arg); } pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 { return interop.getStrAttribute(self, attribute, .{}); } pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void { interop.setIntAttribute(self, attribute, .{}, arg); } pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 { return interop.getIntAttribute(self, attribute, .{}); } pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void { interop.setBoolAttribute(self, attribute, .{}, arg); } pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool { return interop.getBoolAttribute(self, attribute, .{}); } pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T { return interop.getPtrAttribute(T, self, attribute, .{}); } pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void { interop.setPtrAttribute(T, self, attribute, .{}, value); } pub fn setHandle(self: *Self, arg: [:0]const u8) void { interop.setHandle(self, arg); } pub fn fromHandleName(handle_name: [:0]const u8) ?*Self { return interop.fromHandleName(Self, handle_name); } /// /// Creates an interface element given its class name and parameters. /// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible. pub fn init() Initializer { var handle = interop.create(Self); if (handle) |valid| { return .{ .ref = @ptrCast(*Self, valid), }; } else { return .{ .ref = undefined, .last_error = Error.NotInitialized }; } } /// /// Displays a dialog in the current position, or changes a control VISIBLE attribute. /// For dialogs it is equivalent to call IupShowXY using IUP_CURRENT. See IupShowXY for more details. /// For other controls, to call IupShow is the same as setting VISIBLE=YES. pub fn show(self: *Self) !void { try interop.show(self); } /// /// Hides an interface element. This function has the same effect as attributing value "NO" to the interface element’s VISIBLE attribute. /// Once a dialog is hidden, either by means of IupHide or by changing the VISIBLE attribute or by means of a click in the window close button, the elements inside this dialog are not destroyed, so that you can show the dialog again. To destroy dialogs, the IupDestroy function must be called. pub fn hide(self: *Self) void { interop.hide(self); } /// /// Destroys an interface element and all its children. /// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed. pub fn deinit(self: *Self) void { interop.destroy(self); } /// /// Creates (maps) the native interface objects corresponding to the given IUP interface elements. /// It will also called recursively to create the native element of all the children in the element's tree. /// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped. /// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup. /// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog. /// Calling IupMap for an already mapped element that is not a dialog does nothing. /// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout. /// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1). /// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible. /// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14). pub fn map(self: *Self) !void { try interop.map(self); } /// /// Adds a tuple of children pub fn appendChildren(self: *Self, tuple: anytype) !void { try Impl(Self).appendChildren(self, tuple); } /// /// Appends a child on this container /// child must be an Element or pub fn appendChild(self: *Self, child: anytype) !void { try Impl(Self).appendChild(self, child); } /// /// Returns a iterator for children elements. pub fn children(self: *Self) ChildrenIterator { return ChildrenIterator.init(self); } /// /// pub fn getDialog(self: *Self) ?*iup.Dialog { return interop.getDialog(self); } /// /// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy. /// Works also for children of a menu that is associated with a dialog. pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element { return interop.getDialogChild(self, byName); } /// /// Updates the size and layout of all controls in the same dialog. /// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning. pub fn refresh(self: *Self) void { Impl(Self).refresh(self); } /// /// COUNT (read-only) (non inheritable): returns the number of tabs. /// Same value returned by IupGetChildCount. /// (since 3.3) pub fn getCount(self: *Self) i32 { return interop.getIntAttribute(self, "COUNT", .{}); } /// /// FGCOLOR: Tabs title color. /// Default: the global attribute DLGFGCOLOR. pub fn getFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "FGCOLOR", .{}); } /// /// FGCOLOR: Tabs title color. /// Default: the global attribute DLGFGCOLOR. pub fn setFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "FGCOLOR", .{}, rgb); } pub fn getHandleName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "HANDLENAME", .{}); } pub fn setHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "HANDLENAME", .{}, arg); } pub fn getTipBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPBGCOLOR", .{}); } pub fn setTipBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPBGCOLOR", .{}, rgb); } pub fn getTipIcon(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPICON", .{}); } pub fn setTipIcon(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPICON", .{}, arg); } pub fn getMaxSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MAXSIZE", .{}); return Size.parse(str); } pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MAXSIZE", .{}, value); } pub fn getScreenPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "SCREENPOSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn getPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "POSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn setPosition(self: *Self, x: i32, y: i32) void { var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self, "POSITION", .{}, value); } pub fn getTip(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIP", .{}); } pub fn setTip(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIP", .{}, arg); } /// /// SHOWCLOSE [Windows and GTK Only] (non inheritable): enables the close /// button on each tab. /// Default value: "NO". /// In Windows the close button imply the classic visual for the control. /// By default when closed the tab is hidden. /// To change that behavior use the TABCLOSE_CB callback. /// (since 3.10) pub fn getShowClose(self: *Self) bool { return interop.getBoolAttribute(self, "SHOWCLOSE", .{}); } /// /// SHOWCLOSE [Windows and GTK Only] (non inheritable): enables the close /// button on each tab. /// Default value: "NO". /// In Windows the close button imply the classic visual for the control. /// By default when closed the tab is hidden. /// To change that behavior use the TABCLOSE_CB callback. /// (since 3.10) pub fn setShowClose(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "SHOWCLOSE", .{}, arg); } pub fn getCanFocus(self: *Self) bool { return interop.getBoolAttribute(self, "CANFOCUS", .{}); } pub fn setCanFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CANFOCUS", .{}, arg); } pub fn getVisible(self: *Self) bool { return interop.getBoolAttribute(self, "VISIBLE", .{}); } pub fn setVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "VISIBLE", .{}, arg); } pub fn zOrder(self: *Self, arg: ?ZOrder) void { if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self, "ZORDER", .{}); } } pub fn getX(self: *Self) i32 { return interop.getIntAttribute(self, "X", .{}); } pub fn getY(self: *Self) i32 { return interop.getIntAttribute(self, "Y", .{}); } pub fn getTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "THEME", .{}); } pub fn setTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "THEME", .{}, arg); } /// /// CHILDOFFSET: Allow to specify a position offset for the child. /// Available for native containers only. /// It will not affect the natural size, and allows to position controls /// outside the client area. /// Format "dxxdy", where dx and dy are integer values corresponding to the /// horizontal and vertical offsets, respectively, in pixels. /// Default: 0x0. /// (since 3.14) pub fn getChildOffset(self: *Self) Size { var str = interop.getStrAttribute(self, "CHILDOFFSET", .{}); return Size.parse(str); } /// /// CHILDOFFSET: Allow to specify a position offset for the child. /// Available for native containers only. /// It will not affect the natural size, and allows to position controls /// outside the client area. /// Format "dxxdy", where dx and dy are integer values corresponding to the /// horizontal and vertical offsets, respectively, in pixels. /// Default: 0x0. /// (since 3.14) pub fn setChildOffset(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "CHILDOFFSET", .{}, value); } /// /// TABTYPE (non inheritable) (creation only in Windows): Indicates the type of /// tab, which can be "TOP", "BOTTOM", "LEFT" or "RIGHT". /// Default is "TOP". /// In Windows, if LEFT or RIGHT then MULTILINE=YES and TABORIENTATION=VERTICAL /// are set, if TOP or BOTTOM then TABORIENTATION=HORIZONTAL is set. /// In Windows, when not TOP, then visual style is removed from tabs. /// In Windows, the Visual Styles work only when TABTYPE is TOP. /// Windows Classic Windows w/ Styles pub fn getTabType(self: *Self) ?TabType { var ret = interop.getStrAttribute(self, "TABTYPE", .{}); if (std.ascii.eqlIgnoreCase("BOTTOM", ret)) return .Bottom; if (std.ascii.eqlIgnoreCase("LEFT", ret)) return .Left; if (std.ascii.eqlIgnoreCase("RIGHT", ret)) return .Right; if (std.ascii.eqlIgnoreCase("TOP", ret)) return .Top; return null; } /// /// TABTYPE (non inheritable) (creation only in Windows): Indicates the type of /// tab, which can be "TOP", "BOTTOM", "LEFT" or "RIGHT". /// Default is "TOP". /// In Windows, if LEFT or RIGHT then MULTILINE=YES and TABORIENTATION=VERTICAL /// are set, if TOP or BOTTOM then TABORIENTATION=HORIZONTAL is set. /// In Windows, when not TOP, then visual style is removed from tabs. /// In Windows, the Visual Styles work only when TABTYPE is TOP. /// Windows Classic Windows w/ Styles pub fn setTabType(self: *Self, arg: ?TabType) void { if (arg) |value| switch (value) { .Bottom => interop.setStrAttribute(self, "TABTYPE", .{}, "BOTTOM"), .Left => interop.setStrAttribute(self, "TABTYPE", .{}, "LEFT"), .Right => interop.setStrAttribute(self, "TABTYPE", .{}, "RIGHT"), .Top => interop.setStrAttribute(self, "TABTYPE", .{}, "TOP"), } else { interop.clearAttribute(self, "TABTYPE", .{}); } } /// /// EXPAND (non inheritable): The default value is "YES". pub fn getExpand(self: *Self) ?Expand { var ret = interop.getStrAttribute(self, "EXPAND", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal; if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical; if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree; if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } /// /// EXPAND (non inheritable): The default value is "YES". pub fn setExpand(self: *Self, arg: ?Expand) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self, "EXPAND", .{}); } } /// /// SIZE (non inheritable): The default size is the smallest size that fits its /// largest child. /// All child elements are considered even invisible ones. pub fn getSize(self: *Self) Size { var str = interop.getStrAttribute(self, "SIZE", .{}); return Size.parse(str); } /// /// SIZE (non inheritable): The default size is the smallest size that fits its /// largest child. /// All child elements are considered even invisible ones. pub fn setSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "SIZE", .{}, value); } pub fn getWId(self: *Self) i32 { return interop.getIntAttribute(self, "WID", .{}); } pub fn getTipMarkup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPMARKUP", .{}); } pub fn setTipMarkup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPMARKUP", .{}, arg); } pub fn getFontSize(self: *Self) i32 { return interop.getIntAttribute(self, "FONTSIZE", .{}); } pub fn setFontSize(self: *Self, arg: i32) void { interop.setIntAttribute(self, "FONTSIZE", .{}, arg); } pub fn getNaturalSize(self: *Self) Size { var str = interop.getStrAttribute(self, "NATURALSIZE", .{}); return Size.parse(str); } pub fn getUserSize(self: *Self) Size { var str = interop.getStrAttribute(self, "USERSIZE", .{}); return Size.parse(str); } pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "USERSIZE", .{}, value); } pub fn getTipDelay(self: *Self) i32 { return interop.getIntAttribute(self, "TIPDELAY", .{}); } pub fn setTipDelay(self: *Self, arg: i32) void { interop.setIntAttribute(self, "TIPDELAY", .{}, arg); } /// /// TABVISIBLEn (non inheritable): Allows to hide a tab. /// n starts at 0. /// When a tab is hidden the tabs indices are not changed. /// Can be Yes or No. /// Default: Yes. /// (since 3.8) pub fn getTabVisible(self: *Self, index: i32) bool { return interop.getBoolAttribute(self, "TABVISIBLE", .{index}); } /// /// TABVISIBLEn (non inheritable): Allows to hide a tab. /// n starts at 0. /// When a tab is hidden the tabs indices are not changed. /// Can be Yes or No. /// Default: Yes. /// (since 3.8) pub fn setTabVisible(self: *Self, index: i32, arg: bool) void { interop.setBoolAttribute(self, "TABVISIBLE", .{index}, arg); } pub fn getPropagateFocus(self: *Self) bool { return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{}); } pub fn setPropagateFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg); } /// /// BGCOLOR: In Windows and in GTK when in Windows, the tab buttons background /// it will be always defined by the system. /// In Windows the default background is different from the dialog background. /// Default: the global attribute DLGBGCOLOR. pub fn getBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BGCOLOR", .{}); } /// /// BGCOLOR: In Windows and in GTK when in Windows, the tab buttons background /// it will be always defined by the system. /// In Windows the default background is different from the dialog background. /// Default: the global attribute DLGBGCOLOR. pub fn setBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BGCOLOR", .{}, rgb); } /// /// VALUE_HANDLE (non inheritable): Changes the current tab by its handle. /// The value passed must be the handle of a child contained in the tabs. /// When the tabs is created, the first element inserted is set as the visible child. /// (since 3.0) pub fn getValueHandle(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "VALUE_HANDLE", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } /// /// VALUE_HANDLE (non inheritable): Changes the current tab by its handle. /// The value passed must be the handle of a child contained in the tabs. /// When the tabs is created, the first element inserted is set as the visible child. /// (since 3.0) pub fn setValueHandle(self: *Self, arg: anytype) !void { interop.setHandleAttribute(self, "VALUE_HANDLE", .{}, arg); } pub fn setValueHandleHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "VALUE_HANDLE", .{}, arg); } /// /// CHILDSIZEALL (non inheritable): compute the natural size using all children. /// If set to NO will compute using only the current tab. /// Default: Yes. /// (since 3.27) pub fn getChildSizeAll(self: *Self) bool { return interop.getBoolAttribute(self, "CHILDSIZEALL", .{}); } /// /// CHILDSIZEALL (non inheritable): compute the natural size using all children. /// If set to NO will compute using only the current tab. /// Default: Yes. /// (since 3.27) pub fn setChildSizeAll(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CHILDSIZEALL", .{}, arg); } /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.27) pub fn getFloating(self: *Self) ?Floating { var ret = interop.getStrAttribute(self, "FLOATING", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } /// /// FLOATING (non inheritable) (at children only): If a child has FLOATING=YES /// then its size and position will be ignored by the layout processing. /// Default: "NO". /// (since 3.27) pub fn setFloating(self: *Self, arg: ?Floating) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self, "FLOATING", .{}); } } pub fn getNormalizerGroup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NORMALIZERGROUP", .{}); } pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg); } pub fn getRasterSize(self: *Self) Size { var str = interop.getStrAttribute(self, "RASTERSIZE", .{}); return Size.parse(str); } pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "RASTERSIZE", .{}, value); } pub fn getTipFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPFGCOLOR", .{}); } pub fn setTipFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPFGCOLOR", .{}, rgb); } pub fn getFontFace(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTFACE", .{}); } pub fn setFontFace(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTFACE", .{}, arg); } /// /// TABORIENTATION (non inheritable): Indicates the orientation of tab text, /// which can be "HORIZONTAL" or "VERTICAL". /// Default is "HORIZONTAL". /// VERTICAL is supported only in GTK and in Windows. /// In Windows, it can NOT be set, it is dependent on the TABTYPE attribute, if /// TABTYPE=LEFT or TABTYPE=RIGHT then TABORIENTATION=VERTICAL, if TABTYPE=TOP /// or TABTYPE=BOTTOM then TABORIENTATION=HORIZONTAL. /// (GTK 2.6) pub fn getTabOrientation(self: *Self) ?TabOrientation { var ret = interop.getStrAttribute(self, "TABORIENTATION", .{}); if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal; if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical; return null; } /// /// TABORIENTATION (non inheritable): Indicates the orientation of tab text, /// which can be "HORIZONTAL" or "VERTICAL". /// Default is "HORIZONTAL". /// VERTICAL is supported only in GTK and in Windows. /// In Windows, it can NOT be set, it is dependent on the TABTYPE attribute, if /// TABTYPE=LEFT or TABTYPE=RIGHT then TABORIENTATION=VERTICAL, if TABTYPE=TOP /// or TABTYPE=BOTTOM then TABORIENTATION=HORIZONTAL. /// (GTK 2.6) pub fn setTabOrientation(self: *Self, arg: ?TabOrientation) void { if (arg) |value| switch (value) { .Horizontal => interop.setStrAttribute(self, "TABORIENTATION", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self, "TABORIENTATION", .{}, "VERTICAL"), } else { interop.clearAttribute(self, "TABORIENTATION", .{}); } } pub fn getName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NAME", .{}); } pub fn setName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NAME", .{}, arg); } /// /// VALUEPOS (non inheritable): Changes the current tab by its position, /// starting at 0. /// When the tabs is created, the first element inserted is set as the visible child. /// In GTK, inside the callback the returned value is still the previous one. /// (since 3.0) pub fn getValuePos(self: *Self) i32 { return interop.getIntAttribute(self, "VALUEPOS", .{}); } /// /// VALUEPOS (non inheritable): Changes the current tab by its position, /// starting at 0. /// When the tabs is created, the first element inserted is set as the visible child. /// In GTK, inside the callback the returned value is still the previous one. /// (since 3.0) pub fn setValuePos(self: *Self, arg: i32) void { interop.setIntAttribute(self, "VALUEPOS", .{}, arg); } /// /// VALUE (non inheritable): Changes the current tab by its name. /// The value passed must be the name of one of the elements contained in the tabs. /// Use IupSetHandle or IupSetAttributeHandle to associate a child to a name. /// In Lua you can also use the element reference directly. pub fn getValue(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "VALUE", .{}); } /// /// VALUE (non inheritable): Changes the current tab by its name. /// The value passed must be the name of one of the elements contained in the tabs. /// Use IupSetHandle or IupSetAttributeHandle to associate a child to a name. /// In Lua you can also use the element reference directly. pub fn setValue(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "VALUE", .{}, arg); } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabImage(self: *Self, index: i32) ?iup.Element { if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg); } pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABIMAGE", .{index}, arg); } /// /// MULTILINE [Windows Only] (non inheritable): Enable multiple lines of tab buttons. /// This will hide the tab scroll and fits to make all tab buttons visible. /// Can be "YES" or "NO". /// Default "NO". /// It is always enabled when TABTYPE=LEFT or TABTYPE=RIGHT. /// (since 3.0) pub fn getMultiline(self: *Self) bool { return interop.getBoolAttribute(self, "MULTILINE", .{}); } /// /// MULTILINE [Windows Only] (non inheritable): Enable multiple lines of tab buttons. /// This will hide the tab scroll and fits to make all tab buttons visible. /// Can be "YES" or "NO". /// Default "NO". /// It is always enabled when TABTYPE=LEFT or TABTYPE=RIGHT. /// (since 3.0) pub fn setMultiline(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MULTILINE", .{}, arg); } /// /// ACTIVE, FONT, SCREENPOSITION, POSITION, CLIENTSIZE, CLIENTOFFSET, MINSIZE, /// MAXSIZE, WID, TIP, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn getActive(self: *Self) bool { return interop.getBoolAttribute(self, "ACTIVE", .{}); } /// /// ACTIVE, FONT, SCREENPOSITION, POSITION, CLIENTSIZE, CLIENTOFFSET, MINSIZE, /// MAXSIZE, WID, TIP, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn setActive(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "ACTIVE", .{}, arg); } pub fn getTipVisible(self: *Self) bool { return interop.getBoolAttribute(self, "TIPVISIBLE", .{}); } pub fn setTipVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg); } pub fn getExpandWeight(self: *Self) f64 { return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{}); } pub fn setExpandWeight(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg); } pub fn getMinSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MINSIZE", .{}); return Size.parse(str); } pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MINSIZE", .{}, value); } pub fn getNTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NTHEME", .{}); } pub fn setNTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NTHEME", .{}, arg); } pub fn getCharSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CHARSIZE", .{}); return Size.parse(str); } pub fn getClientSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CLIENTSIZE", .{}); return Size.parse(str); } pub fn getClientOffset(self: *Self) Size { var str = interop.getStrAttribute(self, "CLIENTOFFSET", .{}); return Size.parse(str); } pub fn getFontStyle(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTSTYLE", .{}); } pub fn setFontStyle(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTSTYLE", .{}, arg); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 { return interop.getStrAttribute(self, "TABTITLE", .{index}); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABTITLE", .{index}, arg); } pub fn getFont(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONT", .{}); } pub fn setFont(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONT", .{}, arg); } /// /// FOCUS_CB: Called when a child of the container gets or looses the focus. /// It is called only if PROPAGATEFOCUS is defined in the child. /// (since 3.23) int function(Ihandle *ih, int focus); [in C]ih:focus_cb(focus: /// number) -> (ret: number) [in Lua] pub fn setFocusCallback(self: *Self, callback: ?OnFocusFn) void { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB"); Handler.setCallback(self, callback); } /// /// TABCHANGE_CB: Callback called when the user changes the current tab. /// It is not called when the current tab is programmatically changed or removed. /// int function(Ihandle* ih, Ihandle* new_tab, Ihandle* old_tab); [in C] /// ih:tabchange_cb(new_tab, old_tab: ihandle) -> (ret: number) [in Lua] pub fn setTabChangeCallback(self: *Self, callback: ?OnTabChangeFn) void { const Handler = CallbackHandler(Self, OnTabChangeFn, "TABCHANGE_CB"); Handler.setCallback(self, callback); } /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub fn setKAnyCallback(self: *Self, callback: ?OnKAnyFn) void { const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY"); Handler.setCallback(self, callback); } /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub fn setHelpCallback(self: *Self, callback: ?OnHelpFn) void { const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB"); Handler.setCallback(self, callback); } /// /// RIGHTCLICK_CB: Callback called when the user clicks on some tab using the /// right mouse button (since 3.10). /// int function(Ihandle* ih, int pos); [in C] ih:rightclick_cb(pos: number) -> /// (ret: number) [in Lua] pub fn setRightClickCallback(self: *Self, callback: ?OnRightClickFn) void { const Handler = CallbackHandler(Self, OnRightClickFn, "RIGHTCLICK_CB"); Handler.setCallback(self, callback); } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: *Self, callback: ?OnMapFn) void { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self, callback); } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: *Self, callback: ?OnEnterWindowFn) void { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self, callback); } /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub fn setDestroyCallback(self: *Self, callback: ?OnDestroyFn) void { const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB"); Handler.setCallback(self, callback); } /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub fn setKillFocusCallback(self: *Self, callback: ?OnKillFocusFn) void { const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB"); Handler.setCallback(self, callback); } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: *Self, callback: ?OnUnmapFn) void { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self, callback); } /// /// TABCHANGEPOS_CB: Callback called when the user changes the current tab. /// Called only when TABCHANGE_CB is not defined. /// (since 3.3) int function(Ihandle* ih, int new_pos, int old_pos); [in C] /// ih:tabchange_cb(new_pos, old_pos: number) -> (ret: number) [in Lua] pub fn setTabChangePosCallback(self: *Self, callback: ?OnTabChangePosFn) void { const Handler = CallbackHandler(Self, OnTabChangePosFn, "TABCHANGEPOS_CB"); Handler.setCallback(self, callback); } /// /// TABCLOSE_CB [Windows and GTK Only]: Callback called when the user clicks on /// the close button (since 3.10). /// Called only when SHOWCLOSE=Yes. /// int function(Ihandle* ih, int pos); [in C] ih:tabclose_cb(pos: number) -> /// (ret: number) [in Lua] pub fn setTabCloseCallback(self: *Self, callback: ?OnTabCloseFn) void { const Handler = CallbackHandler(Self, OnTabCloseFn, "TABCLOSE_CB"); Handler.setCallback(self, callback); } /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub fn setGetFocusCallback(self: *Self, callback: ?OnGetFocusFn) void { const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB"); Handler.setCallback(self, callback); } pub fn setLDestroyCallback(self: *Self, callback: ?OnLDestroyFn) void { const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB"); Handler.setCallback(self, callback); } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: *Self, callback: ?OnLeaveWindowFn) void { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self, callback); } pub fn setPostMessageCallback(self: *Self, callback: ?OnPostMessageFn) void { const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB"); Handler.setCallback(self, callback); } }; test "Tabs FgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getFgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Tabs HandleName" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setHandleName("Hello").unwrap()); defer item.deinit(); var ret = item.getHandleName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs TipBgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTipBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Tabs TipIcon" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTipIcon("Hello").unwrap()); defer item.deinit(); var ret = item.getTipIcon(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs MaxSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setMaxSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMaxSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Tabs Position" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setPosition(9, 10).unwrap()); defer item.deinit(); var ret = item.getPosition(); try std.testing.expect(ret.x == 9 and ret.y == 10); } test "Tabs Tip" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTip("Hello").unwrap()); defer item.deinit(); var ret = item.getTip(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs ShowClose" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setShowClose(true).unwrap()); defer item.deinit(); var ret = item.getShowClose(); try std.testing.expect(ret == true); } test "Tabs CanFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setCanFocus(true).unwrap()); defer item.deinit(); var ret = item.getCanFocus(); try std.testing.expect(ret == true); } test "Tabs Visible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setVisible(true).unwrap()); defer item.deinit(); var ret = item.getVisible(); try std.testing.expect(ret == true); } test "Tabs Theme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs ChildOffset" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setChildOffset(9, 10).unwrap()); defer item.deinit(); var ret = item.getChildOffset(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Tabs TabType" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTabType(.Bottom).unwrap()); defer item.deinit(); var ret = item.getTabType(); try std.testing.expect(ret != null and ret.? == .Bottom); } test "Tabs Expand" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setExpand(.Yes).unwrap()); defer item.deinit(); var ret = item.getExpand(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Tabs Size" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Tabs TipMarkup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTipMarkup("Hello").unwrap()); defer item.deinit(); var ret = item.getTipMarkup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs FontSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setFontSize(42).unwrap()); defer item.deinit(); var ret = item.getFontSize(); try std.testing.expect(ret == 42); } test "Tabs UserSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setUserSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getUserSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Tabs TipDelay" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTipDelay(42).unwrap()); defer item.deinit(); var ret = item.getTipDelay(); try std.testing.expect(ret == 42); } test "Tabs TabVisible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTabVisible(0, true).unwrap()); defer item.deinit(); var ret = item.getTabVisible(0); try std.testing.expect(ret == true); } test "Tabs PropagateFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setPropagateFocus(true).unwrap()); defer item.deinit(); var ret = item.getPropagateFocus(); try std.testing.expect(ret == true); } test "Tabs BgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Tabs ChildSizeAll" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setChildSizeAll(true).unwrap()); defer item.deinit(); var ret = item.getChildSizeAll(); try std.testing.expect(ret == true); } test "Tabs Floating" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setFloating(.Yes).unwrap()); defer item.deinit(); var ret = item.getFloating(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Tabs NormalizerGroup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setNormalizerGroup("Hello").unwrap()); defer item.deinit(); var ret = item.getNormalizerGroup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs RasterSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setRasterSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getRasterSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Tabs TipFgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTipFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipFgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Tabs FontFace" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setFontFace("Hello").unwrap()); defer item.deinit(); var ret = item.getFontFace(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs TabOrientation" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTabOrientation(.Horizontal).unwrap()); defer item.deinit(); var ret = item.getTabOrientation(); try std.testing.expect(ret != null and ret.? == .Horizontal); } test "Tabs Name" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setName("Hello").unwrap()); defer item.deinit(); var ret = item.getName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs ValuePos" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setValuePos(42).unwrap()); defer item.deinit(); var ret = item.getValuePos(); try std.testing.expect(ret == 42); } test "Tabs Value" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setValue("Hello").unwrap()); defer item.deinit(); var ret = item.getValue(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs Multiline" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setMultiline(true).unwrap()); defer item.deinit(); var ret = item.getMultiline(); try std.testing.expect(ret == true); } test "Tabs Active" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setActive(true).unwrap()); defer item.deinit(); var ret = item.getActive(); try std.testing.expect(ret == true); } test "Tabs TipVisible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTipVisible(true).unwrap()); defer item.deinit(); var ret = item.getTipVisible(); try std.testing.expect(ret == true); } test "Tabs ExpandWeight" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setExpandWeight(3.14).unwrap()); defer item.deinit(); var ret = item.getExpandWeight(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Tabs MinSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setMinSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMinSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Tabs NTheme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setNTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getNTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs FontStyle" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setFontStyle("Hello").unwrap()); defer item.deinit(); var ret = item.getFontStyle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs TabTitle" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setTabTitle(0, "Hello").unwrap()); defer item.deinit(); var ret = item.getTabTitle(0); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Tabs Font" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Tabs.init().setFont("Hello").unwrap()); defer item.deinit(); var ret = item.getFont(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); }
src/elements/tabs.zig
const std = @import("std"); const assert = std.debug.assert; const L = std.unicode.utf8ToUtf16LeStringLiteral; const w = @import("windows.zig"); const BYTE = w.BYTE; const HRESULT = w.HRESULT; const WINAPI = w.WINAPI; const UINT32 = w.UINT32; const BOOL = w.BOOL; const FALSE = w.FALSE; const WCHAR = w.WCHAR; const GUID = w.GUID; const ULONG = w.ULONG; const wasapi = @import("wasapi.zig"); const WAVEFORMATEX = wasapi.WAVEFORMATEX; pub const MIN_CHANNELS: UINT32 = 1; pub const MAX_CHANNELS: UINT32 = 64; pub const MIN_FRAMERATE: UINT32 = 1000; pub const MAX_FRAMERATE: UINT32 = 200000; pub const REGISTRATION_STRING_LENGTH: UINT32 = 256; pub const FLAG_CHANNELS_MUST_MATCH: UINT32 = 0x00000001; pub const FLAG_FRAMERATE_MUST_MATCH: UINT32 = 0x00000002; pub const FLAG_BITSPERSAMPLE_MUST_MATCH: UINT32 = 0x00000004; pub const FLAG_BUFFERCOUNT_MUST_MATCH: UINT32 = 0x00000008; pub const FLAG_INPLACE_REQUIRED: UINT32 = 0x00000020; pub const FLAG_INPLACE_SUPPORTED: UINT32 = 0x00000010; pub const REGISTRATION_PROPERTIES = packed struct { clsid: GUID, FriendlyName: [REGISTRATION_STRING_LENGTH]WCHAR, CopyrightInfo: [REGISTRATION_STRING_LENGTH]WCHAR, MajorVersion: UINT32, MinorVersion: UINT32, Flags: UINT32, MinInputBufferCount: UINT32, MaxInputBufferCount: UINT32, MinOutputBufferCount: UINT32, MaxOutputBufferCount: UINT32, }; pub const LOCKFORPROCESS_BUFFER_PARAMETERS = packed struct { pFormat: *const WAVEFORMATEX, MaxFrameCount: UINT32, }; pub const BUFFER_FLAGS = enum(UINT32) { SILENT, VALID, }; pub const PROCESS_BUFFER_PARAMETERS = packed struct { pBuffer: *anyopaque, BufferFlags: BUFFER_FLAGS, ValidFrameCount: UINT32, }; pub fn IXAPOVTable(comptime T: type) type { return extern struct { unknown: w.IUnknown.VTable(T), xapo: extern struct { GetRegistrationProperties: fn (*T, **REGISTRATION_PROPERTIES) callconv(WINAPI) HRESULT, IsInputFormatSupported: fn ( *T, *const WAVEFORMATEX, *const WAVEFORMATEX, ?**WAVEFORMATEX, ) callconv(WINAPI) HRESULT, IsOutputFormatSupported: fn ( *T, *const WAVEFORMATEX, *const WAVEFORMATEX, ?**WAVEFORMATEX, ) callconv(WINAPI) HRESULT, Initialize: fn (*T, ?*const anyopaque, UINT32) callconv(WINAPI) HRESULT, Reset: fn (*T) callconv(WINAPI) void, LockForProcess: fn ( *T, UINT32, ?[*]const LOCKFORPROCESS_BUFFER_PARAMETERS, UINT32, ?[*]const LOCKFORPROCESS_BUFFER_PARAMETERS, ) callconv(WINAPI) HRESULT, UnlockForProcess: fn (*T) callconv(WINAPI) void, Process: fn ( *T, UINT32, ?[*]const PROCESS_BUFFER_PARAMETERS, UINT32, ?[*]PROCESS_BUFFER_PARAMETERS, BOOL, ) callconv(WINAPI) void, CalcInputFrames: fn (*T, UINT32) callconv(WINAPI) UINT32, CalcOutputFrames: fn (*T, UINT32) callconv(WINAPI) UINT32, }, }; } pub const IID_IXAPO = GUID.parse("{A410B984-9839-4819-A0BE-2856AE6B3ADB}"); pub const IXAPO = extern struct { v: *const IXAPOVTable(Self), const Self = @This(); usingnamespace w.IUnknown.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { return extern struct { pub inline fn GetRegistrationProperties(self: *T, props: **REGISTRATION_PROPERTIES) HRESULT { return self.v.xapo.GetRegistrationProperties(self, props); } pub inline fn IsInputFormatSupported( self: *T, output_format: *const WAVEFORMATEX, requested_input_format: *const WAVEFORMATEX, supported_input_format: ?**WAVEFORMATEX, ) HRESULT { return self.v.xapo.IsInputFormatSupported( self, output_format, requested_input_format, supported_input_format, ); } pub inline fn IsOutputFormatSupported( self: *T, input_format: *const WAVEFORMATEX, requested_output_format: *const WAVEFORMATEX, supported_output_format: ?**WAVEFORMATEX, ) HRESULT { return self.v.xapo.IsOutputFormatSupported( self, input_format, requested_output_format, supported_output_format, ); } pub inline fn Initialize(self: *T, data: ?*const anyopaque, data_size: UINT32) HRESULT { return self.v.xapo.Initialize(self, data, data_size); } pub inline fn Reset(self: *T) void { self.v.xapo.Reset(self); } pub inline fn LockForProcess( self: *T, num_input_params: UINT32, input_params: ?[*]const LOCKFORPROCESS_BUFFER_PARAMETERS, num_output_params: UINT32, output_params: ?[*]const LOCKFORPROCESS_BUFFER_PARAMETERS, ) HRESULT { return self.v.xapo.LockForProcess( self, num_input_params, input_params, num_output_params, output_params, ); } pub inline fn UnlockForProcess(self: *T) void { self.v.xapo.UnlockForProcess(self); } pub inline fn Process( self: *T, num_input_params: UINT32, input_params: ?[*]const PROCESS_BUFFER_PARAMETERS, num_output_params: UINT32, output_params: ?[*]PROCESS_BUFFER_PARAMETERS, is_enabled: BOOL, ) void { return self.v.xapo.Process( self, num_input_params, input_params, num_output_params, output_params, is_enabled, ); } pub inline fn CalcInputFrames(self: *T, num_output_frames: UINT32) UINT32 { return self.v.xapo.CalcInputFrames(self, num_output_frames); } pub inline fn CalcOutputFrames(self: *T, num_input_frames: UINT32) UINT32 { return self.v.xapo.CalcOutputFrames(self, num_input_frames); } }; } }; pub fn IXAPOParametersVTable(comptime T: type) type { return extern struct { unknown: w.IUnknown.VTable(T), params: extern struct { SetParameters: fn (*T, *const anyopaque, UINT32) callconv(WINAPI) void, GetParameters: fn (*T, *anyopaque, UINT32) callconv(WINAPI) void, }, }; } pub const IXAPOParameters = extern struct { v: *const IXAPOParametersVTable(Self), const Self = @This(); usingnamespace w.IUnknown.Methods(Self); usingnamespace Methods(Self); pub fn Methods(comptime T: type) type { return extern struct { pub inline fn SetParameters(self: *T, params: *const anyopaque, size: UINT32) void { self.v.params.SetParameters(self, params, size); } pub inline fn GetParameters(self: *T, params: *anyopaque, size: UINT32) void { self.v.params.GetParameters(self, params, size); } }; } }; pub const E_FORMAT_UNSUPPORTED = @bitCast(HRESULT, @as(c_ulong, 0x88970001)); pub const Error = error{ E_FORMAT_UNSUPPORTED, };
modules/platform/vendored/zwin32/src/xapo.zig
const std = @import("std"); const mem = std.mem; const os = std.os; const Token = std.zig.Token; const ast = std.zig.ast; const TokenIndex = std.zig.ast.TokenIndex; pub const Color = enum { Auto, Off, On, }; pub const Msg = struct { path: []const u8, text: []u8, first_token: TokenIndex, last_token: TokenIndex, tree: *ast.Tree, }; /// `path` must outlive the returned Msg /// `tree` must outlive the returned Msg /// Caller owns returned Msg and must free with `allocator` pub fn createFromParseError( allocator: *mem.Allocator, parse_error: *const ast.Error, tree: *ast.Tree, path: []const u8, ) !*Msg { const loc_token = parse_error.loc(); var text_buf = try std.Buffer.initSize(allocator, 0); defer text_buf.deinit(); var out_stream = &std.io.BufferOutStream.init(&text_buf).stream; try parse_error.render(&tree.tokens, out_stream); const msg = try allocator.create(Msg{ .tree = tree, .path = path, .text = text_buf.toOwnedSlice(), .first_token = loc_token, .last_token = loc_token, }); errdefer allocator.destroy(msg); return msg; } pub fn printToStream(stream: var, msg: *const Msg, color_on: bool) !void { const first_token = msg.tree.tokens.at(msg.first_token); const last_token = msg.tree.tokens.at(msg.last_token); const start_loc = msg.tree.tokenLocationPtr(0, first_token); const end_loc = msg.tree.tokenLocationPtr(first_token.end, last_token); if (!color_on) { try stream.print( "{}:{}:{}: error: {}\n", msg.path, start_loc.line + 1, start_loc.column + 1, msg.text, ); return; } try stream.print( "{}:{}:{}: error: {}\n{}\n", msg.path, start_loc.line + 1, start_loc.column + 1, msg.text, msg.tree.source[start_loc.line_start..start_loc.line_end], ); try stream.writeByteNTimes(' ', start_loc.column); try stream.writeByteNTimes('~', last_token.end - first_token.start); try stream.write("\n"); } pub fn printToFile(file: *os.File, msg: *const Msg, color: Color) !void { const color_on = switch (color) { Color.Auto => file.isTty(), Color.On => true, Color.Off => false, }; var stream = &std.io.FileOutStream.init(file).stream; return printToStream(stream, msg, color_on); }
src-self-hosted/errmsg.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ines = @import("ines.zig"); const Cart = @import("cart.zig").Cart; const Ppu = @import("ppu.zig").Ppu; const Cpu = @import("cpu.zig").Cpu; const Apu = @import("apu.zig").Apu; const Controller = @import("controller.zig").Controller; const video = @import("video.zig"); const audio = @import("audio.zig"); pub const Precision = enum { fast, accurate, }; pub const IoMethod = enum { pure, sdl, }; pub const Config = struct { precision: Precision, method: IoMethod, }; pub fn Console(comptime config: Config) type { return struct { const Self = @This(); allocator: *Allocator, cart: Cart(config), ppu: Ppu(config), cpu: Cpu(config), apu: Apu(config), controller: Controller(config.method), paused: bool, pixel_buffer: *video.PixelBuffer(config.method), audio_context: *audio.Context(config.method), pub fn alloc() Self { return Self{ .allocator = undefined, .cart = undefined, .ppu = undefined, .cpu = undefined, .apu = undefined, .controller = undefined, .paused = undefined, .pixel_buffer = undefined, .audio_context = undefined, }; } pub fn init( self: *Self, allocator: *Allocator, pixel_buffer: *video.PixelBuffer(config.method), audio_context: *audio.Context(config.method), ) void { self.allocator = allocator; self.cart = Cart(config).init(); self.ppu = Ppu(config).init(self, pixel_buffer); self.cpu = Cpu(config).init(self); self.apu = Apu(config).init(self, audio_context); self.controller = Controller(config.method){}; self.paused = true; self.pixel_buffer = pixel_buffer; self.audio_context = audio_context; } pub fn deinit(self: Self) void { self.cart.deinit(self.allocator); self.ppu.deinit(); self.cpu.deinit(); } pub fn loadRom(self: *Self, path: []const u8) !void { var info = try ines.RomInfo.readFile(self.allocator, path); defer info.deinit(self.allocator); try self.cart.loadRom(self.allocator, self, &info); self.cpu.reset(); self.paused = false; } pub fn clearState(self: *Self) void { self.deinit(); self.init(self.allocator, self.pixel_buffer, self.audio_context); } }; }
src/console.zig
const std = @import("std"); const gpa = std.heap.c_allocator; const zfetch = @import("zfetch"); const u = @import("./../../util/index.zig"); const zpm = @import("./../zpm.zig"); // // pub fn execute(args: [][]u8) !void { const url = "https://zpm.random-projects.net/api/packages"; const req = try zfetch.Request.init(gpa, url, null); defer req.deinit(); try req.do(.GET, null, null); const r = req.reader(); const body_content = try r.readAllAlloc(gpa, std.math.maxInt(usize)); var stream = std.json.TokenStream.init(body_content); const val = try std.json.parse([]zpm.Package, &stream, .{ .allocator = gpa }); const found = blk: { for (val) |pkg| { if (std.mem.eql(u8, pkg.name, args[0])) { break :blk pkg; } } u.assert(false, "no package with name '{s}' found", .{args[0]}); unreachable; }; u.assert(found.root_file != null, "package must have an entry point to be able to be added to your dependencies", .{}); const self_module = try u.ModFile.init(gpa, "zig.mod"); for (self_module.deps) |dep| { if (std.mem.eql(u8, dep.name, found.name)) { std.log.warn("dependency with name '{s}' already exists in your dependencies", .{found.name}); } } for (self_module.devdeps) |dep| { if (std.mem.eql(u8, dep.name, found.name)) { std.log.warn("dependency with name '{s}' already exists in your dev_dependencies", .{found.name}); } } const has_zigdotmod = blk: { const _url = try std.mem.join(gpa, "/", &.{ found.git, "blob", "HEAD", "zig.mod" }); const _req = try zfetch.Request.init(gpa, _url, null); defer _req.deinit(); try _req.do(.GET, null, null); break :blk _req.status.code == 200; }; const file = try std.fs.cwd().openFile("zig.mod", .{ .read = true, .write = true }); try file.seekTo(try file.getEndPos()); const file_w = file.writer(); try file_w.print("\n", .{}); try file_w.print(" - src: git {s}\n", .{std.mem.trimRight(u8, found.git, ".git")}); if (!has_zigdotmod) { try file_w.print(" name: {s}\n", .{found.name}); try file_w.print(" main: {s}\n", .{found.root_file.?[1..]}); } std.log.info("Successfully added package {s} by {s}", .{ found.name, found.author }); }
src/cmd/zpm/add.zig
const c = @import("glfw"); const gl = @import("gl"); pub const WindowError = error { InitializationError }; const std = @import("std"); const zalgebra = @import("zalgebra"); const Vec2 = zalgebra.Vec2; var mainWindow: ?*Window = null; // TODO: more inputs and a more efficient way to do them pub const Input = struct { nativeId: *c.GLFWwindow, lastMousePos: Vec2 = Vec2.zero(), mouseDelta: Vec2 = Vec2.zero(), firstFrame: bool = true, pub const KEY_A = c.GLFW_KEY_A; pub const KEY_D = c.GLFW_KEY_D; pub const KEY_S = c.GLFW_KEY_S; pub const KEY_W = c.GLFW_KEY_W; pub const KEY_ESCAPE = c.GLFW_KEY_ESCAPE; pub const KEY_SPACE = c.GLFW_KEY_SPACE; pub const KEY_UP = c.GLFW_KEY_UP; pub const KEY_LEFT = c.GLFW_KEY_LEFT; pub const KEY_RIGHT = c.GLFW_KEY_RIGHT; pub const KEY_DOWN = c.GLFW_KEY_DOWN; pub const MouseInputMode = enum { Normal, Hidden, Grabbed }; pub const MouseButton = enum { Left, Middle, Right }; pub const Joystick = struct { id: u4, name: []const u8, /// This doesn't necessarily means the joystick *IS* a gamepad, this means it is registered in the DB. isGamepad: bool, pub const ButtonType = enum { A, B, X, Y, LeftBumper, RightBumper, Back, Start, Guide, LeftThumb, RightThumb, DPad_Up, DPad_Right, DPad_Down, DPad_Left }; pub fn getRawAxes(self: *const Joystick) []const f32 { var count: c_int = 0; const axes = c.glfwGetJoystickAxes(self.id, &count); return axes[0..@intCast(usize, count)]; } pub fn getRawButtons(self: *const Joystick) []bool { var count: c_int = 0; const cButtons = c.glfwGetJoystickButtons(self.id, &count); var cButtonsBool: [15]bool = undefined; var i: usize = 0; while (i < count) { cButtonsBool[i] = cButtons[i] == c.GLFW_PRESS; i += 1; } return cButtonsBool[0..@intCast(usize, count)]; } pub fn getAxes(self: *const Joystick) []const f32 { if (self.isGamepad) { var state: c.GLFWgamepadstate = undefined; _ = c.glfwGetGamepadState(self.id, &state); return state.axes[0..6]; } else { return self.getRawAxes(); } } pub fn isButtonDown(self: *const Joystick, btn: ButtonType) bool { const buttons = self.getButtons(); return buttons[@enumToInt(btn)]; } pub fn getButtons(self: *const Joystick) []bool { if (self.isGamepad) { var state: c.GLFWgamepadstate = undefined; _ = c.glfwGetGamepadState(self.id, &state); var buttons: [15]bool = undefined; for (state.buttons[0..15]) |value, i| { buttons[i] = value == c.GLFW_PRESS; } return buttons[0..]; } else { return self.getRawButtons(); } } }; fn init(self: *const Input) void { c.glfwSetInputMode(self.nativeId, c.GLFW_STICKY_MOUSE_BUTTONS, c.GLFW_TRUE); } /// Returns true if the key is currently being pressed. pub fn isKeyDown(self: *const Input, key: u32) bool { return c.glfwGetKey(self.nativeId, @intCast(c_int, key)) == c.GLFW_PRESS; } pub fn getJoystick(self: *const Input, id: u4) ?Joystick { _ = self; if (c.glfwJoystickPresent(@intCast(c_int, id)) == c.GLFW_FALSE) { return null; } else { const gamepad = c.glfwJoystickIsGamepad(id) == c.GLFW_TRUE; const cName = if (gamepad) c.glfwGetJoystickName(id) else c.glfwGetGamepadName(id); var i: usize = 0; while (true) { if (cName[i] == 0) break; i += 1; } const name = cName[0..i]; return Joystick { .id = id, .name = name, .isGamepad = gamepad }; } } pub fn isMouseButtonDown(self: *const Input, button: MouseButton) bool { var glfwButton: c_int = 0; switch (button) { .Left => glfwButton = c.GLFW_MOUSE_BUTTON_LEFT, .Middle => glfwButton = c.GLFW_MOUSE_BUTTON_MIDDLE, .Right => glfwButton = c.GLFW_MOUSE_BUTTON_RIGHT } return c.glfwGetMouseButton(self.nativeId, glfwButton) == c.GLFW_PRESS; } pub fn getMousePosition(self: *const Input) Vec2 { var xpos: f64 = 0; var ypos: f64 = 0; c.glfwGetCursorPos(self.nativeId, &xpos, &ypos); return Vec2.new(@floatCast(f32, xpos), @floatCast(f32, ypos)); } /// Set the input mode of the mouse. /// This allows to grab, hide or reset to normal the cursor. pub fn setMouseInputMode(self: *const Input, mode: MouseInputMode) void { var glfwMode: c_int = 0; switch (mode) { .Normal => glfwMode = c.GLFW_CURSOR_NORMAL, .Hidden => glfwMode = c.GLFW_CURSOR_HIDDEN, .Grabbed => glfwMode = c.GLFW_CURSOR_DISABLED } c.glfwSetInputMode(self.nativeId, c.GLFW_CURSOR, glfwMode); } pub fn getMouseInputMode(self: *const Input) MouseInputMode { var mode: c_int = c.glfwGetInputMode(self.nativeId, c.GLFW_CURSOR); switch (mode) { c.GLFW_CURSOR_NORMAL => return .Normal, c.GLFW_CURSOR_HIDDEN => return .Hidden, c.GLFW_CURSOR_DISABLED => return .Grabbed, else => { // this cannot happen return .Normal; } } } pub fn update(self: *Input) void { const pos = self.getMousePosition(); if (self.firstFrame) { self.lastMousePos = pos; self.firstFrame = false; } self.mouseDelta = pos.sub(self.lastMousePos); self.lastMousePos = pos; } }; pub const Window = struct { nativeId: *c.GLFWwindow, /// The input context of the window input: Input, /// Create a new window /// By default, the window will be resizable, with empty title and a size of 800x600. pub fn create() !Window { if (c.glfwInit() != 1) { std.debug.print("Could not init GLFW!\n", .{}); return WindowError.InitializationError; } c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 3); c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE); c.glfwWindowHint(c.GLFW_RESIZABLE, c.GLFW_TRUE); const window = c.glfwCreateWindow(800, 600, "", null, null) orelse { std.debug.print("Could not create GLFW window!\n", .{}); return WindowError.InitializationError; }; c.glfwMakeContextCurrent(window); if (gl.gladLoadGL() < 0) { std.debug.panic("Failed to init Glad GL Loader", .{}); } else { std.debug.print("loaded glad\n", .{}); } c.glfwSwapInterval(1); return Window { .nativeId = window, .input = .{ .nativeId = window } }; } pub fn setSize(self: *const Window, width: u32, height: u32) void { c.glfwSetWindowSize(self.nativeId, @intCast(c_int, width), @intCast(c_int, height)); } pub fn setPosition(self: *const Window, x: i32, y: i32) void { c.glfwSetWindowPos(self.nativeId, @intCast(c_int, x), @intCast(c_int, y)); } pub fn setTitle(self: *const Window, title: [:0]const u8) void { c.glfwSetWindowTitle(self.nativeId, title); } pub fn getPosition(self: *const Window) Vec2 { var x: i32 = 0; var y: i32 = 0; c.glfwGetWindowPos(self.nativeId, &y, &x); return Vec2.new(@intToFloat(f32, x), @intToFloat(f32, y)); } pub fn getSize(self: *const Window) Vec2 { var width: i32 = 0; var height: i32 = 0; c.glfwGetWindowSize(self.nativeId, &width, &height); return Vec2.new(@intToFloat(f32, width), @intToFloat(f32, height)); } pub fn getFramebufferSize(self: *const Window) Vec2 { var width: i32 = 0; var height: i32 = 0; c.glfwGetFramebufferSize(self.nativeId, &width, &height); return Vec2.new(@intToFloat(f32, width), @intToFloat(f32, height)); } pub fn makeContextCurrent(self: *Window) void { c.glfwMakeContextCurrent(self.nativeId); } pub fn setMain(self: *Window) void { mainWindow = self; } pub fn setShouldClose(self: *Window, value: bool) void { c.glfwSetWindowShouldClose(self.nativeId, if (value) 1 else 0); } /// Poll events, swap buffer and update input. /// Returns false if the window should be closed and true otherwises. pub fn update(self: *Window) bool { self.makeContextCurrent(); c.glfwSwapBuffers(self.nativeId); c.glfwPollEvents(); self.input.update(); return c.glfwWindowShouldClose(self.nativeId) == 0; } pub fn deinit(self: *Window) void { _ = self; c.glfwTerminate(); } }; var ctxLock: std.Thread.Mutex = .{}; /// Ensure the GL (or any other API) context is correctly set. /// This method should be called after and inside anything that is async. pub fn windowContextLock(where: i32) @TypeOf(ctxLock) { if (mainWindow) |win| { win.makeContextCurrent(); } else { std.log.scoped(.didot).warn("Could not switch context, no main window!", .{}); } // std.debug.print("CtxLock {}\n", .{where}); _ = where; ctxLock.lock(); return ctxLock; } pub fn windowContextUnlock(where: i32) void { // std.debug.print("CtxUnlock {}\n", .{where}); _ = where; ctxLock.unlock(); } comptime { std.testing.refAllDecls(Window); std.testing.refAllDecls(Input); }
didot-glfw/window.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const unicode = std.unicode; const ascii = @import("ascii.zig"); pub usingnamespace @import("components.zig"); const Self = @This(); pub fn isAlphabetic(cp: u21) bool { return Self.DerivedCoreProperties.isAlphabetic(cp); } pub fn isAsciiAlphabetic(cp: u21) bool { return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z'); } pub fn isAlphaNum(cp: u21) bool { return isAlphabetic(cp) or isNumber(cp); } pub fn isAsciiAlphaNum(cp: u21) bool { return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z') or (cp >= '0' and cp <= '9'); } /// isCased detects cased code points, usually letters. pub fn isCased(cp: u21) bool { return Self.Letter.isCased(cp); } /// isCasedStr returns true when all code points in `s` can be mapped to a different case. pub fn isCasedStr(s: []const u8) !bool { var iter = (try unicode.Utf8View.init(s)).iterator(); return while (iter.nextCodepoint()) |cp| { if (!isCased(cp)) break false; } else true; } test "Ziglyph isCasedStr" { try testing.expect(try isCasedStr("abc")); try testing.expect(!try isCasedStr("abc123")); try testing.expect(!try isCasedStr("123")); } /// isDecimal detects all Unicode decimal numbers. pub fn isDecimal(cp: u21) bool { return Self.Number.isDecimal(cp); } /// isDigit detects all Unicode digits, which curiosly don't include the ASCII digits. pub fn isDigit(cp: u21) bool { return Self.Number.isDigit(cp); } pub fn isAsciiDigit(cp: u21) bool { return cp >= '0' and cp <= '9'; } /// isGraphic detects any code point that can be represented graphically, including spaces. pub fn isGraphic(cp: u21) bool { return isPrint(cp) or isWhiteSpace(cp); } pub fn isAsciiGraphic(cp: u21) bool { return ascii.isGraph(@intCast(u8, cp)); } // isHex detects hexadecimal code points. pub fn isHexDigit(cp: u21) bool { return Self.Number.isHexDigit(cp); } pub fn isAsciiHexDigit(cp: u21) bool { return (cp >= 'a' and cp <= 'f') or (cp >= 'A' and cp <= 'F') or (cp >= '0' and cp <= '9'); } /// isPrint detects any code point that can be printed, excluding spaces. pub fn isPrint(cp: u21) bool { return isAlphaNum(cp) or isMark(cp) or isPunct(cp) or isSymbol(cp) or isWhiteSpace(cp); } pub fn isAsciiPrint(cp: u21) bool { return ascii.isPrint(@intCast(u8, cp)); } pub fn isControl(cp: u21) bool { return Self.DerivedGeneralCategory.isControl(cp); } pub fn isAsciiControl(cp: u21) bool { return ascii.isCntrl(@intCast(u8, cp)); } pub fn isLetter(cp: u21) bool { return Self.Letter.isLetter(cp); } pub fn isAsciiLetter(cp: u21) bool { return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z'); } /// isLower detects code points that are lowercase. pub fn isLower(cp: u21) bool { return Self.Letter.isLower(cp); } pub fn isAsciiLower(cp: u21) bool { return cp >= 'a' and cp <= 'z'; } /// isLowerStr returns true when all code points in `s` are lowercase. pub fn isLowerStr(s: []const u8) !bool { var iter = (try unicode.Utf8View.init(s)).iterator(); return while (iter.nextCodepoint()) |cp| { if (isCased(cp) and !isLower(cp)) break false; } else true; } test "Ziglyph isLowerStr" { try testing.expect(try isLowerStr("abc")); try testing.expect(try isLowerStr("abc123")); try testing.expect(!try isLowerStr("Abc123")); } /// isMark detects special code points that serve as marks in different alphabets. pub fn isMark(cp: u21) bool { return Self.Mark.isMark(cp); } pub fn isNumber(cp: u21) bool { return Self.Number.isNumber(cp); } pub fn isAsciiNumber(cp: u21) bool { return cp >= '0' and cp <= '9'; } /// isPunct detects punctuation characters. Note some punctuation may be considered as symbols by Unicode. pub fn isPunct(cp: u21) bool { return Self.Punct.isPunct(cp); } pub fn isAsciiPunct(cp: u21) bool { return ascii.isPunct(@intCast(u8, cp)); } /// isWhiteSpace detects code points that have the Unicode *WhiteSpace* property. pub fn isWhiteSpace(cp: u21) bool { return Self.PropList.isWhiteSpace(cp); } pub fn isAsciiWhiteSpace(cp: u21) bool { return ascii.isSpace(@intCast(u8, cp)); } // isSymbol detects symbols which may include code points commonly considered punctuation. pub fn isSymbol(cp: u21) bool { return Self.Symbol.isSymbol(cp); } pub fn isAsciiSymbol(cp: u21) bool { return ascii.isSymbol(@intCast(u8, cp)); } /// isTitle detects code points in titlecase. pub fn isTitle(cp: u21) bool { return Self.Letter.isTitle(cp); } /// isUpper detects code points in uppercase. pub fn isUpper(cp: u21) bool { return Self.Letter.isUpper(cp); } pub fn isAsciiUpper(cp: u21) bool { return cp >= 'A' and cp <= 'Z'; } /// isUpperStr returns true when all code points in `s` are uppercase. pub fn isUpperStr(s: []const u8) !bool { var iter = (try unicode.Utf8View.init(s)).iterator(); return while (iter.nextCodepoint()) |cp| { if (isCased(cp) and !isUpper(cp)) break false; } else true; } test "Ziglyph isUpperStr" { try testing.expect(try isUpperStr("ABC")); try testing.expect(try isUpperStr("ABC123")); try testing.expect(!try isUpperStr("abc123")); } /// toLower returns the lowercase code point for the given code point. It returns the same /// code point given if no mapping exists. pub fn toLower(cp: u21) u21 { return Self.Letter.toLower(cp); } pub fn toAsciiLower(cp: u21) u21 { return if (cp >= 'A' and cp <= 'Z') cp ^ 32 else cp; } /// toCaseFoldStr returns the lowercase version of `s`. Caller must free returned memory with `allocator`. pub fn toCaseFoldStr(allocator: *std.mem.Allocator, s: []const u8) ![]u8 { var result = std.ArrayList(u8).init(allocator); defer result.deinit(); var buf: [4]u8 = undefined; var iter = (try unicode.Utf8View.init(s)).iterator(); while (iter.nextCodepoint()) |cp| { const cf = Self.Letter.toCaseFold(cp); for (cf) |cfcp| { if (cfcp == 0) break; const len = try unicode.utf8Encode(cfcp, &buf); try result.appendSlice(buf[0..len]); } } return result.toOwnedSlice(); } test "Ziglyph toCaseFoldStr" { var allocator = std.testing.allocator; const got = try toCaseFoldStr(allocator, "AbC123\u{0390}"); defer allocator.free(got); try testing.expect(std.mem.eql(u8, "abc123\u{03B9}\u{0308}\u{0301}", got)); } /// toLowerStr returns the lowercase version of `s`. Caller must free returned memory with `allocator`. pub fn toLowerStr(allocator: *std.mem.Allocator, s: []const u8) ![]u8 { var result = std.ArrayList(u8).init(allocator); defer result.deinit(); var buf: [4]u8 = undefined; var iter = (try unicode.Utf8View.init(s)).iterator(); while (iter.nextCodepoint()) |cp| { const len = try unicode.utf8Encode(toLower(cp), &buf); try result.appendSlice(buf[0..len]); } return result.toOwnedSlice(); } test "Ziglyph toLowerStr" { var allocator = std.testing.allocator; const got = try toLowerStr(allocator, "AbC123"); defer allocator.free(got); try testing.expect(std.mem.eql(u8, "abc123", got)); } /// toTitle returns the titlecase code point for the given code point. It returns the same /// code point given if no mapping exists. pub fn toTitle(cp: u21) u21 { return Self.Letter.toTitle(cp); } /// toTitleStr returns the titlecase version of `s`. Caller must free returned memory with `allocator`. pub fn toTitleStr(allocator: *std.mem.Allocator, s: []const u8) ![]u8 { var words = try Self.WordIterator.init(allocator, s); defer words.deinit(); var result = std.ArrayList(u8).init(allocator); defer result.deinit(); var buf: [4]u8 = undefined; while (words.next()) |word| { var code_points = Self.CodePointIterator{ .bytes = word.bytes }; var got_f = false; while (code_points.next()) |cp| { var len: usize = 0; if (!got_f and isCased(cp.scalar)) { // First cased is titlecase. len = try unicode.utf8Encode(toTitle(cp.scalar), &buf); got_f = true; } else if (isCased(cp.scalar)) { // Subsequent cased are lowercase. len = try unicode.utf8Encode(toLower(cp.scalar), &buf); } else { // Uncased remain the same. len = try unicode.utf8Encode(cp.scalar, &buf); } try result.appendSlice(buf[0..len]); } } return result.toOwnedSlice(); } test "Ziglyph toTitleStr" { var allocator = std.testing.allocator; const got = try toTitleStr(allocator, "the aBc123 broWn. fox"); defer allocator.free(got); try testing.expectEqualStrings("The Abc123 Brown. Fox", got); } /// toUpper returns the uppercase code point for the given code point. It returns the same /// code point given if no mapping exists. pub fn toUpper(cp: u21) u21 { return Self.Letter.toUpper(cp); } pub fn toAsciiUpper(cp: u21) u21 { return if (cp >= 'a' and cp <= 'z') cp ^ 32 else cp; } /// toUpperStr returns the uppercase version of `s`. Caller must free returned memory with `allocator`. pub fn toUpperStr(allocator: *std.mem.Allocator, s: []const u8) ![]u8 { var result = std.ArrayList(u8).init(allocator); defer result.deinit(); var buf: [4]u8 = undefined; var iter = (try unicode.Utf8View.init(s)).iterator(); while (iter.nextCodepoint()) |cp| { const len = try unicode.utf8Encode(toUpper(cp), &buf); try result.appendSlice(buf[0..len]); } return result.toOwnedSlice(); } test "Ziglyph toUpperStr" { var allocator = std.testing.allocator; const got = try toUpperStr(allocator, "aBc123"); defer allocator.free(got); try testing.expect(std.mem.eql(u8, "ABC123", got)); } test "Ziglyph ASCII methods" { const z = 'F'; try testing.expect(isAsciiAlphabetic(z)); try testing.expect(isAsciiAlphaNum(z)); try testing.expect(isAsciiHexDigit(z)); try testing.expect(isAsciiGraphic(z)); try testing.expect(isAsciiPrint(z)); try testing.expect(isAsciiUpper(z)); try testing.expect(!isAsciiControl(z)); try testing.expect(!isAsciiDigit(z)); try testing.expect(!isAsciiNumber(z)); try testing.expect(!isAsciiLower(z)); try testing.expectEqual(toAsciiLower(z), 'f'); try testing.expectEqual(toAsciiUpper('a'), 'A'); try testing.expect(isAsciiLower(toAsciiLower(z))); } test "Ziglyph struct" { const z = 'z'; try testing.expect(isAlphaNum(z)); try testing.expect(!isControl(z)); try testing.expect(!isDecimal(z)); try testing.expect(!isDigit(z)); try testing.expect(!isHexDigit(z)); try testing.expect(isGraphic(z)); try testing.expect(isLetter(z)); try testing.expect(isLower(z)); try testing.expect(!isMark(z)); try testing.expect(!isNumber(z)); try testing.expect(isPrint(z)); try testing.expect(!isPunct(z)); try testing.expect(!isWhiteSpace(z)); try testing.expect(!isSymbol(z)); try testing.expect(!isTitle(z)); try testing.expect(!isUpper(z)); const uz = toUpper(z); try testing.expect(isUpper(uz)); try testing.expectEqual(uz, 'Z'); const lz = toLower(uz); try testing.expect(isLower(lz)); try testing.expectEqual(lz, 'z'); const tz = toTitle(lz); try testing.expect(isUpper(tz)); try testing.expectEqual(tz, 'Z'); } test "Ziglyph isGraphic" { try testing.expect(isGraphic('A')); try testing.expect(isGraphic('\u{20E4}')); try testing.expect(isGraphic('1')); try testing.expect(isGraphic('?')); try testing.expect(isGraphic(' ')); try testing.expect(isGraphic('=')); try testing.expect(!isGraphic('\u{0003}')); } test "Ziglyph isHexDigit" { var cp: u21 = '0'; while (cp <= '9') : (cp += 1) { try testing.expect(isHexDigit(cp)); } cp = 'A'; while (cp <= 'F') : (cp += 1) { try testing.expect(isHexDigit(cp)); } cp = 'a'; while (cp <= 'f') : (cp += 1) { try testing.expect(isHexDigit(cp)); } try testing.expect(!isHexDigit('\u{0003}')); try testing.expect(!isHexDigit('Z')); } test "Ziglyph isPrint" { try testing.expect(isPrint('A')); try testing.expect(isPrint('\u{20E4}')); try testing.expect(isPrint('1')); try testing.expect(isPrint('?')); try testing.expect(isPrint('=')); try testing.expect(isPrint(' ')); try testing.expect(isPrint('\t')); try testing.expect(!isPrint('\u{0003}')); } test "Ziglyph isAlphaNum" { var cp: u21 = '0'; while (cp <= '9') : (cp += 1) { try testing.expect(isAlphaNum(cp)); } cp = 'a'; while (cp <= 'z') : (cp += 1) { try testing.expect(isAlphaNum(cp)); } cp = 'A'; while (cp <= 'Z') : (cp += 1) { try testing.expect(isAlphaNum(cp)); } try testing.expect(!isAlphaNum('=')); } test "Ziglyph isControl" { try testing.expect(isControl('\t')); try testing.expect(isControl('\u{0008}')); try testing.expect(isControl('\u{0012}')); try testing.expect(isControl('\n')); try testing.expect(isControl('\r')); try testing.expect(!isControl('A')); }
src/Ziglyph.zig