diff --git a/.gitignore b/.gitignore index aa9e88c..109ebb0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ /.vscode -/__pycache__ +/**/__pycache__ /codegen.txt +/jupyter +/broma_ida/types/codegen.hpp diff --git a/BromaIDA.py b/BromaIDA.py index e1a2f78..4b2bd03 100644 --- a/BromaIDA.py +++ b/BromaIDA.py @@ -28,7 +28,8 @@ def bida_main(): """BromaIDA main entrypoint""" import_export_prompt = popup( "Import", "Export", "", - "Import or Export Broma file?" + "Import or Export Broma file?\n" + "(Please make sure Extras.bro is in the same directory)" ) if import_export_prompt == ASKBTN_BTN1: @@ -86,7 +87,7 @@ class BromaIDAPlugin(ida_plugin_t): """BromaIDA Plugin""" flags = PLUGIN_PROC | PLUGIN_HIDE comment = "Broma support for IDA." - help = "Ctrl-Shift-I to start the importing/exporting." + help = f"{PLUGIN_HOTKEY} to start the importing/exporting." wanted_name = PLUGIN_NAME wanted_hotkey = PLUGIN_HOTKEY diff --git a/README.md b/README.md index e3348af..7d8611b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,13 @@ Parses a Broma file and exports the bindings into a Broma file/imports the bindi - IDA 7.0 or higher - IDAPython Python v3.0.0 support +- If you want to be able to import types: + - IDAClang + - MSVC + +## Features + +TODO ## Installation diff --git a/broma_ida/broma/argtype.py b/broma_ida/broma/argtype.py new file mode 100644 index 0000000..e9331f8 --- /dev/null +++ b/broma_ida/broma/argtype.py @@ -0,0 +1,289 @@ +from typing import cast, overload, Union, Optional, TypedDict, Literal + +from re import split, match, sub + + +class BaseArgType(TypedDict): + """A type. Has a register, a name and an actual type.""" + name: str + type: str + reg: Optional[str] + + +class BaseShortArgType(TypedDict): + """A type. Has an (optional) register, a name and an actual type.""" + name: str + type: str + + +BASE_EXPANDED_STL_TYPES = { + "std::vector": "<{}, std::allocator<{}>>", + "std::map": + "<{0}, {1}, std::less<{0}>, std::allocator>>", # noqa: E501 + "std::unordered_map": + "<{0}, {1}, std::hash<{0}>, std::equal_to<{0}>, std::allocator>>", # noqa: E501 + "std::set": "<{}, std::less<{}>, std::allocator<{}>>", + "std::unordered_set": + "<{}, std::hash<{}>, std::equal_to<{}>, std::allocator<{}>>" +} + +EXPANDED_STL_TYPES = { + "std::string": + "std::basic_string, std::allocator>" +} + + +class ArgType: + """An argument type""" + btype: BaseArgType + + def _expand_stl_type(self, t: str) -> str: + """Expands STL types because IDA is retarded and likes to expand them + + Args: + t (str): _description_ + + Returns: + str: _description_ + """ + # IDA likes spaces after types + format_pointer = lambda pt: sub(r"([^ ])\*", r"\1 *", pt) # noqa: E731 + + if "std::" not in t: + return t + + if t == "std::string": + return t + + if t.startswith("std::vector"): + split_type = match(r"std::vector<(.*)>", t) + + assert split_type is not None, "impossible" + + if split_type.group(1) in EXPANDED_STL_TYPES: + return format_pointer(f"""std::vector{ + BASE_EXPANDED_STL_TYPES["std::vector"] + }""".replace( + "{}", + EXPANDED_STL_TYPES[split_type.group(1)] # type: ignore + )) + + # this should never happen, but it causes the below code + # to go ham + if "std::allocator" in t: + return t + + # "it just works" + # credit to henrysck075 i couldnt figure out this shit :D + ret = t + vec_to_contained = [[ret, ret]] + while True: + try: + ret = match(r"std::vector<(.+)>", ret) + + if ret is None: + break + + ret = ret.group(1) + except IndexError: + break + vec_to_contained.append([ret, ret]) + + split_type = vec_to_contained[-1][0] + vec_to_contained[-2][1] = vec_to_contained[-2][1].replace( + f"<{split_type}>", + BASE_EXPANDED_STL_TYPES["std::vector"].replace( + "{}", split_type + ) + ) + + for i in reversed(range(len(vec_to_contained) - 2)): + expanded_vec = vec_to_contained[i+1][1] + vec_to_contained[i][1] = vec_to_contained[i][1].replace( + f"<{vec_to_contained[i+1][0]}>", + BASE_EXPANDED_STL_TYPES["std::vector"].replace( + "{}", expanded_vec + ) + ) + + return format_pointer(vec_to_contained[0][1]) + + if t.startswith("std::map"): + split_type = split(r"std::map<(.*), (.*)>", t) + map_key_type = "" + map_value_type = "" + + # key or value is an STL type that has 2 template args + if "," in split_type[1] and split_type[2].endswith(">"): + map_key_type = split_type[1][:split_type[1].index(" ") - 1] + map_value_type = f"""{ + split_type[1][split_type[1].index(" ") + 1:] + }, { + split_type[2] + }""" + else: + map_key_type = split_type[1] + map_value_type = split_type[2] + + if map_key_type in EXPANDED_STL_TYPES or \ + map_value_type in EXPANDED_STL_TYPES: + key_is_stl = map_key_type in EXPANDED_STL_TYPES + value_is_stl = map_value_type in EXPANDED_STL_TYPES + + return format_pointer(f"""std::map{ + BASE_EXPANDED_STL_TYPES["std::map"] + }""".replace( + "{0}", + EXPANDED_STL_TYPES[map_key_type] + if key_is_stl else map_key_type + ).replace( + "{1}", + EXPANDED_STL_TYPES[map_value_type] + if value_is_stl else map_value_type + )) + + # std::map is never used as key + if any([ + x in map_value_type for x in BASE_EXPANDED_STL_TYPES.keys() + ]): + return format_pointer(f"""std::map{ + BASE_EXPANDED_STL_TYPES["std::map"] + }""".replace( + "{0}", map_key_type + ).replace( + "{1}", self._expand_stl_type(map_value_type) + )) + + return format_pointer(f"""std::map{ + BASE_EXPANDED_STL_TYPES["std::map"] + }""".replace( + "{0}", map_key_type + ).replace( + "{1}", map_value_type + )) + + if t.startswith("std::unordered_map"): + split_type = split(r"std::unordered_map<(.*), (.*)>", t) + map_key_type = "" + map_value_type = "" + + if "," in split_type[1] and split_type[2].endswith(">"): + map_key_type = split_type[1][:split_type[1].index(" ") - 1] + map_value_type = f"""{ + split_type[1][split_type[1].index(" ") + 1:] + }, { + split_type[2] + }""" + else: + map_key_type = split_type[1] + map_value_type = split_type[2] + + if map_key_type in EXPANDED_STL_TYPES or \ + map_value_type in EXPANDED_STL_TYPES: + key_is_stl = map_key_type in EXPANDED_STL_TYPES + value_is_stl = map_value_type in EXPANDED_STL_TYPES + + return format_pointer(f"""std::unordered_map{ + BASE_EXPANDED_STL_TYPES["std::unordered_map"] + }""".replace( + "{0}", + EXPANDED_STL_TYPES[map_key_type] + if key_is_stl else map_key_type + ).replace( + "{1}", + EXPANDED_STL_TYPES[map_value_type] + if value_is_stl else map_value_type + )) + + # std::unordered_map is never used as key + if any([ + x in map_value_type for x in BASE_EXPANDED_STL_TYPES.keys() + ]): + return format_pointer(f"""std::unordered_map{ + BASE_EXPANDED_STL_TYPES["std::unordered_map"] + }""".replace( + "{0}", map_key_type + ).replace( + "{1}", self._expand_stl_type(map_value_type) + )) + + return format_pointer(f"""std::unordered_map{ + BASE_EXPANDED_STL_TYPES["std::unordered_map"] + }""".replace( + "{0}", map_key_type + ).replace( + "{1}", map_value_type + )) + + if t.startswith("std::set"): + contained = match("std::set<(.*)>", t) + + assert contained is not None, "impossible" + + return format_pointer(f"""std::set{ + BASE_EXPANDED_STL_TYPES["std::set"] + }""".replace( + "{}", contained.group(1) + )) + + if t.startswith("std::unordered_set"): + contained = match("std::unordered_set<(.*)>", t) + + assert contained is not None, "impossible" + + return format_pointer(f"""std::unordered_set{ + BASE_EXPANDED_STL_TYPES["std::unordered_set"] + }""".replace( + "{}", contained.group(1) + )) + + raise BaseException(f"[!] Couldn't expand STL type: {t}") + + def __init__(self, btype: Union[BaseArgType, BaseShortArgType]): + if btype.get("reg"): + self.btype = cast(BaseArgType, btype) + else: + self.btype = { + "name": btype["name"], + "type": btype["type"], + "reg": None + } + + self.btype["type"] = self._expand_stl_type(self.btype["type"]) + + def __str__(self) -> str: + if self.btype["name"] == "": + return self.btype["type"] + + return f"""{self.btype["type"]} {self.btype["name"]}{ + f"@<{self.btype['reg']}>" if self.btype["reg"] is not None else "" + }""" + + def __eq__(self, key: object) -> bool: + if isinstance(key, str): + return self.btype["type"] == key + + return False + + @overload + def __getitem__( + self, + key: Literal[ + "name", "type" + ] + ) -> str: + ... + + @overload + def __getitem__(self, key: Literal["reg"]) -> Optional[str]: + ... + + def __getitem__(self, key): + return self.btype.__getitem__(key) + + def __setitem__(self, key, value): + self.btype[key] = value + + +class RetType(ArgType): + """A return type""" diff --git a/broma_ida/broma/binding.py b/broma_ida/broma/binding.py index 4a252a6..e12063e 100644 --- a/broma_ida/broma/binding.py +++ b/broma_ida/broma/binding.py @@ -1,43 +1,72 @@ -from typing import Union, TypedDict, Literal, cast +from typing import cast, overload, Union, TypedDict, Literal -from pybroma import Type +from ida_name import is_visible_cp + +from broma_ida.broma.constants import BROMA_CALLING_CONVENTIONS +from broma_ida.broma.argtype import ArgType, RetType class BaseBindingType(TypedDict): """Base binding type""" name: str - className: str - qualifiedName: str - idaQualifiedName: str + class_name: str + qualified_name: str + ida_qualified_name: str address: int - return_type: Type - parameters: dict[str, Type] + return_type: RetType + parameters: list[ArgType] + calling_convention: BROMA_CALLING_CONVENTIONS + is_virtual: bool + is_static: bool class BaseShortBindingType(TypedDict): """Base binding type (but shorter)""" name: str - className: str + class_name: str address: int class BaseShortBindingTypeWithMD(BaseShortBindingType): """Base binding type (shorter, with metadata about the function)""" - return_type: Type - parameters: dict[str, Type] + return_type: RetType + parameters: list[ArgType] + calling_convention: BROMA_CALLING_CONVENTIONS + is_virtual: bool + is_static: bool class Binding: """Actual binding type. Implements __eq__ because TypedDict can't be instantiated, and as such, can't have overridden methods - TODO: figure out a way to narrow down the return type of __getitem__ - to stop putting type: ignore everywhere """ binding: BaseBindingType is_overload: bool + def _get_ida_qualified_name( + self, + binding: Union[ + BaseShortBindingType, BaseShortBindingTypeWithMD + ] + ) -> str: + """Get's the IDA qualified name of a binding. + (because "~" is not allowed in a method's name, + unless you modify NameChars in ida.cfg) + + Args: + binding (BaseShortBindingType | BaseShortBindingTypeWithMD): + The binding + + Returns: + str: _description_ + """ + if not is_visible_cp(ord("~")) and \ + binding["class_name"] == binding["name"][1:]: + return f"""{binding["class_name"]}::d{binding["class_name"]}""" + return f"""{binding["class_name"]}::{binding["name"]}""" + def __init__( self, binding: Union[ @@ -45,7 +74,7 @@ def __init__( ], is_overload: bool = False ) -> None: - if binding.get("qualifiedName") is not None: + if binding.get("qualified_name") is not None: self.binding = cast(BaseBindingType, binding) else: binding = cast(BaseShortBindingType, binding) @@ -55,16 +84,19 @@ def __init__( self.binding = BaseBindingType({ "name": binding["name"], - "className": binding["className"], - "qualifiedName": - f"""{binding["className"]}::{binding["name"]}""", - "idaQualifiedName": - f"""{binding["className"]}::{binding["name"]}""".replace( - "::~", "::d" - ), + "class_name": binding["class_name"], + "qualified_name": + f"""{binding["class_name"]}::{binding["name"]}""", + "ida_qualified_name": self._get_ida_qualified_name(binding), "address": binding["address"], - "return_type": binding.get("return_type") or Type(), - "parameters": binding.get("parameters") or {} + "return_type": binding.get("return_type") or RetType({ + "name": "", "type": "", "reg": "" + }), + "parameters": binding.get("parameters") or [], + "calling_convention": + binding.get("calling_convention") or "default", + "is_virtual": binding.get("is_virtual") or False, + "is_static": binding.get("is_static") or False }) self.is_overload = is_overload @@ -73,34 +105,70 @@ def __eq__(self, key: object) -> bool: if isinstance(key, int): return self.binding["address"] == key elif isinstance(key, str): - return self.binding["qualifiedName"] == key + return self.binding["qualified_name"] == key return False + @overload def __getitem__( self, key: Literal[ - "name", "className", "qualifiedName", - "idaQualifiedName", "address", "return_type", - "parameters" + "name", "class_name", "qualified_name", + "ida_qualified_name" ] - ) -> Union[str, list[str], int, bool]: - return self.binding.__getitem__(key) # type: ignore + ) -> str: + ... + + @overload + def __getitem__(self, key: Literal["address"]) -> int: + ... + + @overload + def __getitem__( + self, + key: Literal["is_virtual", "is_static"] + ) -> bool: + ... + + @overload + def __getitem__(self, key: Literal["parameters"]) -> list[ArgType]: + ... + + @overload + def __getitem__(self, key: Literal["return_type"]) -> RetType: + ... + + @overload + def __getitem__( + self, + key: Literal["calling_convention"] + ) -> BROMA_CALLING_CONVENTIONS: + ... + + def __getitem__(self, key): + return self.binding.__getitem__(key) + + def __setitem__(self, key, value): + self.binding[key] = value def __str__(self) -> str: - return f"""name={self.binding["name"]}""" \ - f"""className={self.binding["className"]}""" \ - f"""qualifiedName={self.binding["qualifiedName"]}""" \ - f"""idaQualifiedName={self.binding["idaQualifiedName"]}""" \ - f"""address={hex(self.binding["address"])} """ \ - f"""is_overload={self.is_overload} """ \ - f"""{self.binding["return_type"]}({ - ', '.join(self.binding["parameters"]) - })""" + return f"""{"virtual " if self.binding["is_virtual"] else ""}""" \ + f"""{"static " if self.binding["is_static"] else ""}""" \ + f"""{self.binding["return_type"]["type"]} """ \ + f"""__{self.binding["calling_convention"]} """ \ + f"""{self.binding["class_name"]}::{self.binding["name"]}""" \ + f"""({", ".join([ + str(arg) for arg in self.binding["parameters"] + ])}) @ {hex(self.binding["address"])}; """ \ + f"""({self.binding["ida_qualified_name"]})""" def __hash__(self) -> int: return hash(( - self.binding["name"], self.binding["className"], - self.binding["qualifiedName"], self.binding["idaQualifiedName"], + self.binding["name"], self.binding["class_name"], + self.binding["qualified_name"], self.binding["ida_qualified_name"], self.binding["address"] )) + + def update(self): + self.binding["ida_qualified_name"] = \ + self._get_ida_qualified_name(self.binding) diff --git a/broma_ida/broma/codegen.py b/broma_ida/broma/codegen.py new file mode 100644 index 0000000..1d4fd36 --- /dev/null +++ b/broma_ida/broma/codegen.py @@ -0,0 +1,128 @@ +from pathlib import Path + +from pybroma import Class, Root + +from broma_ida.broma.constants import BROMA_PLATFORMS +from broma_ida.class_builder.class_builder import ClassBuilder + + +class BromaCodegen: + """Codegen for Broma""" + FILE_HEADER = """// Generated by BromaIDA, do not modify +#include + +#define STR_CONCAT_WRAPPER(a, b) a ## b +#define STR_CONCAT(a, b) STR_CONCAT_WRAPPER(a, b) +#define PAD(size) unsigned char STR_CONCAT(__pad, __LINE__)[size]\n\n""" + + _classes: dict[str, Class] + _path: Path + _target_platform: BROMA_PLATFORMS + _broma_path: Path + + _added_classes: set[str] = set() + + def __init__( + self, + platform: BROMA_PLATFORMS, + broma_classes: dict[str, Class], + path: Path, + broma_path: Path + ): + self._target_platform = platform + self._classes = broma_classes + self._path = path + self._broma_path = broma_path + + def write(self): + """_summary_ + + Args: + path (Path): _description_ + """ + with open( + self._path / "codegen.hpp", + "w", + buffering=10*1024*1024 + ) as f: + f.write(self.FILE_HEADER) + + with open(self._path / "enums.hpp") as enums: + f.write("// enums.hpp\n") + for line in enums.readlines(): + f.write(line) + f.write("\n\n") + + with open(self._path / "cocos2d.hpp") as cocos: + f.write("// cocos2d.hpp\n") + for line in cocos.readlines(): + f.write(line) + f.write("\n\n") + + with open(self._path / "fmod.hpp") as fmod: + f.write("// fmod.hpp\n") + for line in fmod.readlines(): + f.write(line) + f.write("\n\n") + + with open(self._path / "stl_types.hpp") as stl_types: + f.write("// stl_types.hpp\n") + for line in stl_types.readlines(): + if line == """#include "enums.hpp"\n""": + continue + + f.write(line) + f.write("\n\n") + + with open(self._path / "helpers.hpp") as helpers: + f.write("// helpers.hpp\n") + for line in helpers.readlines(): + f.write(line) + f.write("\n\n") + + f.flush() + + # now we codegen the Broma file + f.write("// Broma\n\n") + + f.write("// typdefs\n") + f.write("using TodoReturn = void; // :troll:\n") + f.write("\n") + + f.write("// extras\n") + for name, broma_class in Root( + str(self._broma_path / "Extras.bro") + ).classesAsDict().items(): + f.write( + ClassBuilder(self._target_platform, broma_class).get_str() + ) + f.write("\n") + + f.write("// class fwddec\n") + f.writelines([f"class {c};\n" for c in self._classes.keys()]) + f.write("\n") + + f.flush() + + f.write("// delegates and non-polymorphic classes\n") + for name, broma_class in self._classes.items(): + if len(broma_class.superclasses) != 0: + continue + + self._added_classes.add(name) + + f.write( + ClassBuilder(self._target_platform, broma_class).get_str() + ) + f.write("\n") + + f.flush() + + f.write("// classes\n") + for name, broma_class in self._classes.items(): + if name in self._added_classes: + continue + + f.write( + ClassBuilder(self._target_platform, broma_class).get_str() + ) diff --git a/broma_ida/broma/constants.py b/broma_ida/broma/constants.py index 0a4a491..f5706d6 100644 --- a/broma_ida/broma/constants.py +++ b/broma_ida/broma/constants.py @@ -2,3 +2,30 @@ # no android32 nor android64 because they have symbols BROMA_PLATFORMS = Literal["win", "mac", "ios"] + +BROMA_CALLING_CONVENTIONS = Literal[ + "default", "thiscall", + "optcall", "membercall" +] + +# not a Broma constant but a constant nonetheless +CALLING_CONVENTIONS = Literal[ + "__thiscall", "__fastcall", + "__cdecl", "__stdcall" +] + +CPP_TYPE_SPECIFIERS = ("unsigned", "signed") +CPP_TYPE_QUALIFIERS = ("const", "volatile") +CPP_DATA_TYPES = ("bool", "char", "short", "int", "long") +CPP_PRIMITIVES = ( + "void", "int", "char", "float", "short", + "double", "bool", "long" +) + +DATA_TYPE_TO_SIZE = { + "long": 8, + "int": 4, + "short": 2, + "char": 1, + "bool": 1 +} diff --git a/broma_ida/broma/exporter.py b/broma_ida/broma/exporter.py index 2cce8bc..32e7580 100644 --- a/broma_ida/broma/exporter.py +++ b/broma_ida/broma/exporter.py @@ -1,4 +1,4 @@ -from typing import cast, Union, Generator, Any +from typing import cast, Optional, Generator, Any from os import path from idaapi import get_imagebase @@ -33,7 +33,7 @@ class BromaExporter: _filepath: str = "" _target_platform: BROMA_PLATFORMS - # { "qualifiedName": Binding } + # { "qualified_name": Binding } bindings: dict[str, Binding] = {} num_exports: int = 0 @@ -50,7 +50,7 @@ def _make_plat_method_addr_regex(self, platform: BROMA_PLATFORMS) -> str: def _parse_method_platforms( self, - platforms: Union[str, None] + platforms: Optional[str] ) -> dict[BROMA_PLATFORMS, int]: """Parses "win 0x13be40, mac 0x586990" to { "win": 0x13be40, "mac": 0x586990 } @@ -99,7 +99,7 @@ def _get_broma_string( parsed_broma_line.string[:-2] } = { self._target_platform - } {hex(binding["address"])};\n""" # type: ignore + } {hex(binding["address"])};\n""" broma_binding_platforms = self._parse_method_platforms( parsed_broma_line.group(5) @@ -109,7 +109,7 @@ def _get_broma_string( if self._target_platform not in broma_binding_platforms: return sub( r"(?:(0[xX][0-9a-fA-F]+);)", - rf"""\1, {self._target_platform} {hex(binding["address"])};""", # type: ignore + rf"""\1, {self._target_platform} {hex(binding["address"])};""", parsed_broma_line.string, 1 ) @@ -119,17 +119,17 @@ def _get_broma_string( if popup( "Overwrite", "Keep", None, "Mismatch in Broma for method " - f"""{binding["qualifiedName"]} """ # type: ignore + f"""{binding["qualified_name"]} """ f"""(Broma: { hex(broma_binding_platforms[self._target_platform]) }. """ - f"""idb: {hex(binding["address"])})\n""" # type: ignore + f"""idb: {hex(binding["address"])})\n""" "Overwrite Broma or Keep?" ) == 1: return sub( self._make_plat_method_addr_regex(self._target_platform), f"{self._target_platform} " - f"""{hex(binding["address"])}""", # type: ignore + f"""{hex(binding["address"])}""", parsed_broma_line.string ) @@ -148,7 +148,7 @@ def push_binding(self, binding: Binding): binding (Binding): The binding to be exported """ self.bindings.update([ - (binding["qualifiedName"], binding) # type: ignore + (binding["qualified_name"], binding) ]) def push_bindings(self, bindings: list[Binding]): @@ -158,7 +158,7 @@ def push_bindings(self, bindings: list[Binding]): bindings (list[Binding]): The list of bindings """ self.bindings.update([ - (binding["qualifiedName"], binding) # type: ignore + (binding["qualified_name"], binding) for binding in bindings ]) @@ -184,7 +184,7 @@ def import_from_idb(self, names: Generator[tuple[Any, Any], Any, None]): self.push_binding(Binding({ "name": split_name[1], - "className": split_name[0], + "class_name": split_name[0], "address": ea - get_imagebase() }, search(r"\S+::\S+_[0-9]+$", name) is not None)) diff --git a/broma_ida/broma/importer.py b/broma_ida/broma/importer.py index dc3dc52..d7b140a 100644 --- a/broma_ida/broma/importer.py +++ b/broma_ida/broma/importer.py @@ -1,47 +1,563 @@ from io import TextIOWrapper +from typing import cast, Optional, Union, Literal from idaapi import get_imagebase from idc import ( get_name as get_ea_name, get_func_flags, get_func_cmt, - set_func_cmt, + set_func_cmt, SetType, FUNC_LIB ) from ida_funcs import get_func, add_func from ida_kernwin import ASKBTN_BTN1, ASKBTN_CANCEL +from ida_typeinf import ( + get_idati, get_ordinal_qty, + func_type_data_t as ida_func_type_data_t, + tinfo_t as ida_tinfo_t +) +from ida_nalt import get_tinfo +from functools import cmp_to_key from re import sub +from pathlib import Path -from pybroma import Root +from pybroma import Root, FunctionBindField, Type, Class -from broma_ida.broma.constants import BROMA_PLATFORMS +from broma_ida.broma.constants import ( + BROMA_PLATFORMS, BROMA_CALLING_CONVENTIONS, + CALLING_CONVENTIONS, CPP_TYPE_QUALIFIERS, + CPP_TYPE_SPECIFIERS, CPP_DATA_TYPES, + CPP_PRIMITIVES, DATA_TYPE_TO_SIZE +) from broma_ida.broma.binding import Binding +from broma_ida.broma.argtype import ArgType, RetType +from broma_ida.broma.codegen import BromaCodegen from broma_ida.utils import ( get_platform_printable, get_short_info, rename_func, popup, stop, - are_args_primitive + are_args_primitive, is_primitive_type, + get_ida_plugin_path ) +g_has_idaclang = False + +try: + from ida_srclang import ( + set_parser_argv, parse_decls_for_srclang, + SRCLANG_CPP + ) + g_has_idaclang = True +except ImportError: + pass + + +class BIUtils: + """BromaImporter utilities""" + @staticmethod + def _get_biggest_type(types: list[str]) -> str: + """_summary_ + + Args: + types (list[str]): _description_ + + Returns: + str: _description_ + """ + biggest_type = "" + last_biggest_size = 0 + + for t in types: + if last_biggest_size < DATA_TYPE_TO_SIZE[t]: + biggest_type = t + last_biggest_size = DATA_TYPE_TO_SIZE[t] + + return biggest_type + + @staticmethod + def get_function_info(ida_ea: int) -> Optional[ida_func_type_data_t]: + """_summary_ + + Args: + ida_ea (int): _description_ + + Returns: + func_type_data_t: _description_ + """ + tif = ida_tinfo_t() + func_info = ida_func_type_data_t() + + if get_tinfo(tif, ida_ea): + if tif.get_func_details(func_info): + return func_info + + return None + + @staticmethod + def get_type_info( + name: str, + update: bool = False + ) -> Optional[ida_tinfo_t]: + """_summary_ + + Args: + name (str): _description_ + update (bool): _description_. Defaults to False. + + Returns: + Optional[ida_tinfo_t]: _description_ + """ + if not hasattr(BIUtils.get_type_info, "types") or update: + BIUtils.get_type_info.types = {} + + idati = get_idati() + tif = ida_tinfo_t() + + for ordinal in range(1, get_ordinal_qty(idati) + 1): + if tif.get_numbered_type(idati, ordinal): + BIUtils.get_type_info.types[tif.get_type_name()] = \ + tif.copy() + + if name in BIUtils.get_type_info.types: + return BIUtils.get_type_info.types[name] + + return None + + @staticmethod + def from_pybroma_args(args: dict[str, Type]) -> list[ArgType]: + """_summary_ + + Args: + args (dict[str, Type]): _description_ + + Returns: + list[ArgType]: _description_ + """ + return [ + ArgType({ + "name": name, + "type": arg_t.name.replace("gd::", "std::") + }) + for name, arg_t in args.items() + ] + + @staticmethod + def simplify_type(t: str) -> str: + """_summary_ + + Args: + t (str): _description_ + + Returns: + str: _description_ + """ + ret = "" + + is_pointer = t.endswith("*") + is_ref = t.endswith("&") + t_no_pref = t.rstrip("*").rstrip("&") if is_pointer or is_ref else t + + if len(t.split(" ")) == 1 and t_no_pref in CPP_TYPE_SPECIFIERS: + if is_pointer: + t = "int*" + elif is_ref: + t = "int&" + else: + t = "int" + + ret = sub( + "|".join([ + rf"(? int: + """_summary_ + + Args: + a (ArgType): _description_ + b (ArgType): _description_ + + Returns: + int: _description_ + """ + a_is_composite = BIUtils.simplify_type(a["type"]) not in CPP_PRIMITIVES + b_is_composite = BIUtils.simplify_type(b["type"]) not in CPP_PRIMITIVES + + if a_is_composite and b_is_composite: + return 0 + + if a_is_composite: + return 1 + + if b_is_composite: + return -1 + + return 0 + + @staticmethod + def init_types() -> bool: + """_summary_""" + if not g_has_idaclang: + return False + + stl_struct = BIUtils.get_type_info("holy_shit") + if stl_struct and stl_struct.get_size() == 0x40C: + return True + + plugin_path = get_ida_plugin_path() + + if plugin_path is None: + print("[!] Plugin path wasn't able to be found!") + popup( + "Ok", "Ok", None, + "Couldn't find plugin path. Please open a GitHub issue." + ) + return False + + types_path = plugin_path / "broma_ida" / "types" + + if set_parser_argv("clang", "-x c++ -target i386-pc-win32") != 0: + print("[!] Clang potentially not found!") + popup( + "Ok", "Ok", None, + "IDAClang is needed to import types!" + ) + return False + + popup( + "Ok", "Ok", None, + "Importing STL Types...\n" + "This will probably freeze IDA for a couple of seconds.\n" + "So don't close the plugin/IDA!\n" + "(This will only happen once, unless new STL types " + "are found in Broma)" + ) + + # sorry... + enum_file = "" + file = "" + + with open(types_path / "enums.hpp", "r") as f: + enum_file = "".join(f.readlines()) + + with open(types_path / "stl_types.hpp", "r") as f: + file = "".join(f.readlines()).replace( + """#include "enums.hpp\"""", enum_file + ) + + if parse_decls_for_srclang(SRCLANG_CPP, None, file, False) != 0: + print( + "[!] Some errors have occurred! " + "If something breaks please make a " + "bug report in the GitHub repository" + ) + + def verify_type(t: Optional[ida_tinfo_t]) -> bool: + if t is None: + return True + + if t.get_size() == 0xFFFFFFFFFFFFFFFF: + return True + + return False + + if any([ + verify_type(BIUtils.get_type_info(t)) + for t in ( + "cocos2d::CCObject", "cocos2d::CCImage", + "cocos2d::CCApplication" + ) + ]): + popup( + "Ok", "Ok", None, + "Importing cocos2d Types...\n" + "This will probably freeze IDA for a couple of seconds, " + "if not minutes.\n" + "So don't close the plugin/IDA!\n" + "(This will only happen once, unless new cocos2d types " + "are found in Broma)" + ) + + if parse_decls_for_srclang( + SRCLANG_CPP, None, + types_path / "cocos2d.hpp", False + ) != 0: + print( + "[!] Some errors have occurred! " + "If something breaks please make a " + "bug report in the GitHub repository" + ) + + return True + + class BromaImporter: """Broma importer of all time using PyBroma now!""" _target_platform: BROMA_PLATFORMS _file_path: str + _has_types: bool bindings: list[Binding] = [] # { 0xaddr: [Binding, Binding, ...] } duplicates: dict[int, list[Binding]] = {} + # Signature specific functions below + def _reorder_args( + self, + binding: Binding + ) -> list[ArgType]: + """Reorders a function's arguments (membercall and optcall shenanigans) + + Args: + binding (Binding): The binding. + + Returns: + list[BType]: Reordered arguments + """ + reordered_args: list[ArgType] = sorted( + binding["parameters"], + key=cmp_to_key(BIUtils.args_comparator) + ) + + xmm_reg = 0 + for i in range(len(reordered_args)): + arg = reordered_args[i] + + if i < 4 and arg["type"] in ["float", "double"]: + reordered_args[i]["reg"] = f"xmm{xmm_reg}" + xmm_reg += 1 + else: + if i == 0 and arg["type"] in CPP_PRIMITIVES: + reordered_args[i]["reg"] = "ecx" + elif binding["calling_convention"] == "optcall" and i == 1 \ + and arg["type"] in CPP_PRIMITIVES: + reordered_args[i]["reg"] = "edx" + else: + # not defined yet type or sm???? + # if type.isNotDefinedYet(): + # ... + + # is manual stack fixing needed? + ... + + return reordered_args + + def _fix_return_type(self, binding: Binding): + """_summary_ + + Args: + binding (Binding): _description_ + """ + if binding["return_type"] == "TodoReturn": + ida_func_info = BIUtils.get_function_info( + get_imagebase() + binding["address"] + ) + binding["return_type"] = RetType({ + "name": "", + "type": ida_func_info.rettype if ida_func_info + else "void" + }) + + return + + if BIUtils.simplify_type(binding["return_type"]["type"]) in \ + ["float", "double"]: + binding["name"] += "@" + else: + if binding["return_type"] != "void": + binding["name"] += "@" + + def _has_mismatch( + self, + function: ida_func_type_data_t, + binding: Binding + ) -> bool: + """Checks if there is a mismatch between the idb and a binding. + + Args: + function (func_type_data_t): + The function signature returned by IDA. + binding (Binding): The binding. + + Returns: + bool + """ + # TODO: impl + return True + + def _get_calling_convention( + self, + function: FunctionBindField + ) -> BROMA_CALLING_CONVENTIONS: + """Ya + + Args: + function (FunctionBindField): The function got hennessy. + + Returns: + BROMA_CALLING_CONVENTIONS + """ + if self._target_platform != "win": + return "default" + + if function.prototype.is_virtual or function.prototype.is_callback: + return "thiscall" + + if function.prototype.is_static: + return "optcall" + + if function.binds.__getattribute__(self._target_platform) != -1: + return "thiscall" + + return "membercall" + + def _get_ida_calling_convention( + self, + convention: BROMA_CALLING_CONVENTIONS + ) -> Union[CALLING_CONVENTIONS, Literal[""]]: + """Gets the real calling convention for a given + Broma calling convention. + + Args: + convention (BROMA_CALLING_CONVENTIONS): The Broma + calling convention. + + Returns: + CALLING_CONVENTIONS: The real one. + """ + if convention == "default": + return "" # let IDA handle it :D + + if convention == "thiscall" or convention == "membercall": + return "__thiscall" + + if convention == "optcall": + return "__fastcall" + + def _get_ida_args_str( + self, + binding: Binding + ) -> str: + """Gets a function's argument string. + + Args: + binding (Binding): The binding + + Returns: + str + """ + this_arg_or_empty: str = "" + + if self._get_ida_calling_convention(binding["calling_convention"]) == \ + "__thiscall": + this_arg_or_empty += f"""{binding["class_name"]}* this""" + if len(binding["parameters"]) > 0: + this_arg_or_empty += ", " + + return this_arg_or_empty + ", ".join([ + str(arg) for arg in binding["parameters"] + ]) + + def _get_function_signature( + self, + binding: Binding + ) -> str: + """Returns a C++ function signature for the given function. + + Args: + binding (Binding): The binding. + + Returns: + str: The C++ function signature + """ + # incase return type register was fixed, update the name + binding.update() + + return \ + f"""{"static " if binding["is_static"] else ""}""" \ + f"""{"virtual " if binding["is_virtual"] else ""}""" \ + f"""{binding["return_type"]["type"]} """ \ + f"""{ + self._get_ida_calling_convention(binding["calling_convention"]) + } """ \ + f"""{binding["ida_qualified_name"]}""" \ + f"""({self._get_ida_args_str(binding)});""" + + def _fix_function(self, binding: Binding): + """_summary_ + + Args: + binding (Binding): _description_ + """ + should_reorder_args = ( + binding["calling_convention"] == "membercall" or + binding["calling_convention"] == "optcall" + ) and any([ + ( + BIUtils.simplify_type(arg["type"]) not in CPP_PRIMITIVES or + BIUtils.simplify_type(arg["type"]) in ["float", "double"] + ) + for arg in binding["parameters"] + ]) + + if should_reorder_args: + binding["parameters"] = self._reorder_args(binding) + + self._fix_return_type(binding) + # End of signature specific functions + + def _codegen_classes(self, classes: dict[str, Class]) -> bool: + """_summary_ + + Args: + classes (dict[str, Class]): _description_ + + Returns: + bool: + """ + if not g_has_idaclang: + return False + + plugin_path = get_ida_plugin_path() + + if plugin_path is None: + popup( + "Ok", "Ok", None, + "TODO" + ) + return False + + BromaCodegen( + self._target_platform, + classes, + plugin_path / "broma_ida" / "types", + Path("".join(Path(self._file_path).parts[:-1])) + ).write() + + return True + def __init__(self, platform: BROMA_PLATFORMS): """Initializes a BromaImporter instance Args: platform (BROMA_PLATFORMS): The target platform """ + self._has_types = BIUtils.init_types() self._reset() self._target_platform = platform def parse_file_stream(self, file: TextIOWrapper): """Parses a .bro file from a file stream + and imports the members and methods Args: file (TextIOWrapper): The file stream @@ -53,6 +569,17 @@ def parse_file_stream(self, file: TextIOWrapper): self._file_path = file.name root = Root(self._file_path) + if g_has_idaclang and popup( + "Yes", "No", None, "Import classes from Broma?" + ) == 1: + if self._codegen_classes(root.classesAsDict()): + parse_decls_for_srclang( + SRCLANG_CPP, + None, + get_ida_plugin_path() / "broma_ida" / "types" / "codegen.hpp", # type: ignore + True + ) + for class_name, broma_class in root.classesAsDict().items(): for field in broma_class.fields: function_field = field.getAsFunctionBindField() @@ -76,17 +603,17 @@ def parse_file_stream(self, file: TextIOWrapper): ] error_location = \ f"{class_name}::{function.name} " \ - f"and {dup_binding['qualifiedName']} " \ + f"and {dup_binding['qualified_name']} " \ f"@ {hex(function_address)}" if f"{class_name}::{function.name}" == \ - dup_binding['qualifiedName']: + dup_binding['qualified_name']: print( "[!] BromaImporter: Duplicate binding with " f"same qualified name! ({error_location})" ) continue - elif class_name == dup_binding['className']: + elif class_name == dup_binding['class_name']: print( "[!] BromaImporter: Duplicate binding within " f"same class! ({error_location})" @@ -96,7 +623,7 @@ def parse_file_stream(self, file: TextIOWrapper): print( "[!] BromaImporter: Duplicate binding! " f"({class_name}::{function.name} " - f"and {dup_binding['qualifiedName']} " + f"and {dup_binding['qualified_name']} " f"@ {hex(function_address)})" ) del self.bindings[self.bindings.index(dup_binding)] @@ -106,19 +633,33 @@ def parse_file_stream(self, file: TextIOWrapper): if function_address in self.duplicates: self.duplicates[function_address].append(Binding({ "name": function.name, - "className": class_name, + "class_name": class_name, "address": function_address, - "return_type": function.ret, - "parameters": function.args + "return_type": RetType({ + "name": "", + "type": function.ret.name + }), + "parameters": BIUtils.from_pybroma_args(function.args), + "calling_convention": + self._get_calling_convention(function_field), + "is_virtual": function.is_virtual, + "is_static": function.is_static })) continue self.bindings.append(Binding({ "name": function.name, - "className": class_name, + "class_name": class_name, "address": function_address, - "return_type": function.ret, - "parameters": function.args + "return_type": RetType({ + "name": "", + "type": function.ret.name + }), + "parameters": BIUtils.from_pybroma_args(function.args), + "calling_convention": + self._get_calling_convention(function_field), + "is_virtual": function.is_virtual, + "is_static": function.is_static })) file.close() @@ -156,19 +697,28 @@ def import_into_idb(self): ) continue - # TODO: finish this - # if are_args_primitive(binding["parameters"]): # type: ignore - # SetType(get_screen_ea(), "") + # are_args_primitive(binding["parameters"]) and + if self._has_types and \ + is_primitive_type(binding["return_type"]["type"]) and \ + self._has_mismatch( + cast( + ida_func_type_data_t, + BIUtils.get_function_info(ida_ea) + ), binding + ): + self._fix_function(binding) + # SetType(ida_ea, self._get_function_signature(binding)) + print(self._get_function_signature(binding)) if ida_name.startswith("sub_"): rename_func( ida_ea, - binding["idaQualifiedName"] # type: ignore + binding["ida_qualified_name"] ) - elif sub("_[0-9]+", "", ida_name) != binding["idaQualifiedName"]: + elif sub("_[0-9]+", "", ida_name) != binding["ida_qualified_name"]: mismatch_popup = popup( "Overwrite", "Keep", "", - f"""Mismatch in Broma ({binding["qualifiedName"]}) """ + f"""Mismatch in Broma ({binding["qualified_name"]}) """ f"and idb ({ida_name})!\n" "Overwrite from Broma or keep current name?" ) @@ -176,26 +726,25 @@ def import_into_idb(self): if mismatch_popup == ASKBTN_BTN1: rename_func( ida_ea, - binding["idaQualifiedName"] # type: ignore + binding["ida_qualified_name"] ) elif mismatch_popup == ASKBTN_CANCEL: stop() - # and now for what took me 3 hours :D + # and now for what took me countless hours of debugging :D for addr, bindings in self.duplicates.items(): ida_ea = get_imagebase() + addr func_cmt = get_func_cmt(ida_ea, True) func_names = ", ".join( - [binding["qualifiedName"] - for binding in bindings] # type: ignore + [binding["qualified_name"] for binding in bindings] ) if func_cmt == "": # use the first occurrence as the name (very good imo) rename_func( ida_ea, - bindings[0]["idaQualifiedName"] # type: ignore + bindings[0]["ida_qualified_name"] ) set_func_cmt(ida_ea, f"Merged with: {func_names}", True) diff --git a/broma_ida/class_builder/class_builder.py b/broma_ida/class_builder/class_builder.py new file mode 100644 index 0000000..d62a997 --- /dev/null +++ b/broma_ida/class_builder/class_builder.py @@ -0,0 +1,94 @@ +from pybroma import Class + +# from broma_ida.broma.constants import BROMA_PLATFORMS +from typing import Literal +BROMA_PLATFORMS = Literal["win", "mac", "ios"] + + +class ClassBuilder: + """Builds a C++ class""" + _class_str: str + _broma_class: Class + _target_platform: BROMA_PLATFORMS + + def _import_class(self): + """_summary_""" + self._class_str = f"class {self._broma_class.name}" + + if len(self._broma_class.superclasses) != 0: + self._class_str += f""" : public { + ", ".join(self._broma_class.superclasses) + }\n{{\npublic:\n""" + else: + self._class_str += "\n{\npublic:\n" + + has_left_functions: bool = False + + for field in self._broma_class.fields: + func_field = field.getAsFunctionBindField() or \ + field.getAsOutOfLineField() + member_field = field.getAsMemberField() + pad_field = field.getAsPadField() + + if func_field is not None and \ + func_field.prototype.is_virtual: + has_left_functions = False + + function = func_field.prototype + self._class_str += f"""\tvirtual { + function.ret.name.replace("gd::", "std::") + } {function.name}({", ".join([ + f"{a.name.replace('gd::', 'std::')} {n}" + for n, a in function.args.items()]) + });\n""" + + # if BIUtils.simplify_type(function.ret.name) not in CPP_PRIMITIVES and \ + # BIUtils.get_type_info(function.ret.name) is None: + # ret_type = function.ret.name[:-1] \ + # if function.ret.name.endswith("*") or \ + # function.ret.name.endswith("&") \ + # else function.ret.name + + has_left_functions = True + + elif member_field is not None: + if has_left_functions: + self._class_str += "\n" + has_left_functions = False + + # currently, only members use the geode namespace + self._class_str += f"""\t{ + member_field.type.name.replace( + "gd::", "std::" + ).replace("geode::", "") + } {member_field.name};\n""" + elif pad_field is not None: + pad_amount = pad_field.amount.__getattribute__( + self._target_platform + ) + + # skip other members because no padding for current platform + if pad_amount == -1: + break + + if has_left_functions: + self._class_str += "\n" + has_left_functions = False + + self._class_str += f"""\tPAD({hex(pad_amount)});\n""" + + self._class_str += "};\n\n" + + def __init__( + self, + platform: BROMA_PLATFORMS, + broma_class: Class + ): + self._target_platform = platform + self._broma_class = broma_class + self._class_str = "" + + self._import_class() + + def get_str(self): + return self._class_str diff --git a/broma_ida/types/cocos2d.hpp b/broma_ida/types/cocos2d.hpp new file mode 100644 index 0000000..fdbd9a7 --- /dev/null +++ b/broma_ida/types/cocos2d.hpp @@ -0,0 +1,5214 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2009 Valentin Milea + Copyright (c) 2011 Zynga Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + Modified by SpaghettDev + ****************************************************************************/ + +#include +#include +#include +#include + +#ifndef PAD +#define STR_CONCAT_WRAPPER(a, b) a ## b +#define STR_CONCAT(a, b) STR_CONCAT_WRAPPER(a, b) +#define PAD(size) unsigned char STR_CONCAT(__pad, __LINE__)[size] +#endif +#define RT_ADD(...) __VA_ARGS__ +#define RT_REMOVE(...) + +// cocos macros +#define CC_PROPERTY_READONLY(varType, varName, funName) \ +protected: varType varName; \ +public: virtual varType get##funName(void); + +#define CC_PROPERTY_READONLY_PASS_BY_REF(varType, varName, funName) \ +protected: varType varName; \ +public: virtual const varType& get##funName(void); + +#define CC_PROPERTY(varType, varName, funName) \ +protected: varType varName; \ +public: virtual varType get##funName(void); \ +public: virtual void set##funName(varType var); + +#define CC_PROPERTY_PASS_BY_REF(varType, varName, funName) \ +protected: varType varName; \ +public: virtual const varType& get##funName(void); \ +public: virtual void set##funName(const varType& var); + +#define CC_SYNTHESIZE_READONLY(varType, varName, funName) \ +protected: varType varName; \ +public: virtual varType get##funName(void) const { return varName; } + +#define CC_SYNTHESIZE_READONLY_NC(varType, varName, funName) \ +protected: varType varName; \ +public: virtual varType get##funName(void) { return varName; } + +#define CC_SYNTHESIZE_READONLY_PASS_BY_REF(varType, varName, funName) \ +protected: varType varName; \ +public: virtual const varType& get##funName(void) const { return varName; } + +#define CC_SYNTHESIZE(varType, varName, funName) \ +protected:varType varName; \ +public: virtual varType get##funName(void) const { return varName; } \ +public: virtual void set##funName(varType var) { varName = var; } + +#define CC_SYNTHESIZE_PASS_BY_REF(varType, varName, funName) \ +protected: varType varName; \ +public: virtual const varType& get##funName(void) const { return varName; } \ +public: virtual void set##funName(const varType& var) { varName = var; } + +#define CC_SYNTHESIZE_RETAIN(varType, varName, funName) \ +private: varType varName; \ +public: virtual varType get##funName(void) const { return varName; } \ +public: \ + virtual void set##funName(varType var) { \ + if (varName != var) { \ + CC_SAFE_RETAIN(var); \ + CC_SAFE_RELEASE(varName); \ + varName = var; \ + } \ + } + +#define CC_SYNTHESIZE_NV(varType, varName, funName) \ +protected: varType varName; \ +public: varType get##funName(void) const { return varName; } \ +public: void set##funName(varType var) { varName = var; } + +#define CC_SYNTHESIZE_READONLY_NV(varType, varName, funName) \ +protected: varType varName; \ +public: varType get##funName(void) const { return varName; } + +#define CC_SYNTHESIZE_READONLY_NV_NC(varType, varName, funName) \ +protected: varType varName; \ +public: varType get##funName(void) { return varName; } + +#define CC_PROPERTY(varType, varName, funName) \ +protected: varType varName; \ +public: virtual varType get##funName(void); \ +public: virtual void set##funName(varType var); + +#define CREATE_FUNC(__TYPE__) \ + static __TYPE__* create() { \ + __TYPE__* pRet = new __TYPE__(); \ + if (pRet && pRet->init()) { \ + pRet->autorelease(); \ + return pRet; \ + } \ + else { \ + delete pRet; \ + pRet = NULL; \ + return NULL; \ + } \ + } + +#define NODE_FUNC(__TYPE__) \ + CC_DEPRECATED_ATTRIBUTE static __TYPE__* node() { \ + __TYPE__* pRet = new __TYPE__(); \ + if (pRet && pRet->init()) { \ + pRet->autorelease(); \ + return pRet; \ + } \ + else { \ + delete pRet; \ + pRet = NULL; \ + return NULL; \ + } \ + } + +#define CC_SAFE_DELETE(p) \ + do { \ + if (p) { \ + delete (p); \ + (p) = 0; \ + } \ + } while (0) + +#define CC_SAFE_DELETE_ARRAY(p) \ + do { \ + if (p) { \ + delete[] (p); \ + (p) = 0; \ + } \ + } while (0) + +#define CC_SAFE_FREE(p) \ + do { \ + if (p) { \ + free(p); \ + (p) = 0; \ + } \ + } while (0) + +#define CC_SAFE_RELEASE(p) \ + do { \ + if (p) { \ + (p)->release(); \ + } \ + } while (0) + +#define CC_SAFE_RELEASE_NULL(p) \ + do { \ + if (p) { \ + (p)->release(); \ + (p) = 0; \ + } \ + } while (0) + +#define CC_SAFE_RETAIN(p) \ + do { \ + if (p) { \ + (p)->retain(); \ + } \ + } while (0) + +#define CC_UNUSED_PARAM(unusedparam) (void)unusedparam +#define CCAssert(cond, msg) ((void)(cond)) + +#if defined(__GNUC__) && (__GNUC__ >= 4) + #define CC_FORMAT_PRINTF(formatPos, argPos) \ + __attribute__((__format__(printf, formatPos, argPos))) +#elif defined(__has_attribute) && !defined(_MSC_VER) + #if __has_attribute(format) + #define CC_FORMAT_PRINTF(formatPos, argPos) \ + __attribute__((__format__(printf, formatPos, argPos))) + #endif +#else + #define CC_FORMAT_PRINTF(formatPos, argPos) +#endif + +#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) + #define CC_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) +#elif _MSC_VER >= 1400 // vs 2005 or higher + #define CC_DEPRECATED_ATTRIBUTE __declspec(deprecated) +#else + #define CC_DEPRECATED_ATTRIBUTE +#endif + + +// kazmath +#define kmScalar float +typedef struct kmMat4 { + kmScalar mat[16]; +} kmMat4; + + +// gl +typedef unsigned int GLenum; +typedef unsigned int GLbitfield; +typedef unsigned int GLuint; +typedef int GLint; +typedef int GLsizei; +typedef unsigned char GLboolean; +typedef signed char GLbyte; +typedef short GLshort; +typedef unsigned char GLubyte; +typedef unsigned short GLushort; +typedef unsigned long GLulong; +typedef float GLfloat; +typedef float GLclampf; +typedef double GLdouble; +typedef double GLclampd; +typedef void GLvoid; + + + +// pugixml +namespace pugi +{ +#ifdef PUGIXML_WCHAR_MODE +# define PUGIXML_TEXT(t) L ## t +# define PUGIXML_CHAR wchar_t +#else +# define PUGIXML_TEXT(t) t +# define PUGIXML_CHAR char +#endif + + typedef PUGIXML_CHAR char_t; + class xml_node; + class xml_attribute_iterator; + struct xml_attribute_struct; + struct xml_node_struct; + + class xml_node + { + friend class xml_attribute_iterator; + friend class xml_node_iterator; + friend class xml_named_node_iterator; + + protected: + xml_node_struct* _root; + + typedef void (*unspecified_bool_type)(xml_node***); + + }; + + class xml_attribute + { + friend class xml_attribute_iterator; + friend class xml_node; + + private: + xml_attribute_struct* _attr; + + typedef void (*unspecified_bool_type)(xml_attribute***); + }; + + class xml_attribute_iterator + { + friend class xml_node; + + private: + mutable xml_attribute _wrap; + xml_node _parent; + }; + + class xml_node_iterator + { + friend class xml_node; + + private: + mutable xml_node _wrap; + xml_node _parent; + }; + + class xml_named_node_iterator + { + private: + mutable xml_node _node; + const char_t* _name; + }; + + class xml_document: public xml_node + { + private: + char_t* _buffer; + + char _memory[192]; + }; +} + + +// cocos2d +class DS_Dictionary +{ +public: + pugi::xml_document doc; + std::vector dictTree; + bool compatible; +}; + +// uthash +struct UT_hash_handle; +typedef struct UT_hash_bucket { + struct UT_hash_handle *hh_head; + unsigned count; + unsigned expand_mult; + +} UT_hash_bucket; +typedef struct UT_hash_table { + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ + uint8_t *bloom_bv; + char bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle { + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +// not in the other cocos2d namespace because they are used extensively +// and i dont want to mix sections +namespace cocos2d +{ + // CCGeometry + class CCPoint + { + public: + float x; + float y; + + CCPoint() + : x(.0f), y(.0f) + {} + + CCPoint(const CCPoint& p) + : x(p.x), y(p.y) + {}; + + CCPoint(float x, float y) + : x(x), y(y) + {}; + }; + + class CCSize + { + public: + float width; + float height; + + inline CCSize() : width(0), height(0) {} + inline CCSize(float width, float height) : width(width), height(height) {} + }; + + class CCRect + { + public: + CCPoint origin; + CCSize size; + }; + + typedef struct _ccColor3B + { + GLubyte r; + GLubyte g; + GLubyte b; + } ccColor3B; + + static const ccColor3B ccWHITE = {255,255,255}; + #define CCPointZero CCPointMake(0,0) + + #define CCPointMake(x, y) cocos2d::CCPoint((float)(x), (float)(y)) + #define CCSizeMake(width, height) cocos2d::CCSize((float)(width), (float)(height)) + #define CCRectMake(x, y, width, height) cocos2d::CCRect((float)(x), (float)(y), (float)(width), (float)(height)) +} + +namespace cocos2d +{ + // enums + enum class CCObjectType { + PlayLayer = 5, + LevelEditorLayer = 6, + GameObject = 13, + MenuLayer = 15, + }; + + typedef enum { + //! 32-bit texture: RGBA8888 + kCCTexture2DPixelFormat_RGBA8888, + //! 24-bit texture: RGBA888 + kCCTexture2DPixelFormat_RGB888, + //! 16-bit texture without Alpha channel + kCCTexture2DPixelFormat_RGB565, + //! 8-bit textures used as masks + kCCTexture2DPixelFormat_A8, + //! 8-bit intensity texture + kCCTexture2DPixelFormat_I8, + //! 16-bit textures used as masks + kCCTexture2DPixelFormat_AI88, + //! 16-bit textures: RGBA4444 + kCCTexture2DPixelFormat_RGBA4444, + //! 16-bit textures: RGB5A1 + kCCTexture2DPixelFormat_RGB5A1, + //! 4-bit PVRTC-compressed texture: PVRTC4 + kCCTexture2DPixelFormat_PVRTC4, + //! 2-bit PVRTC-compressed texture: PVRTC2 + kCCTexture2DPixelFormat_PVRTC2, + + + //! Default texture format: RGBA8888 + kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888, + + // backward compatibility stuff + kTexture2DPixelFormat_RGBA8888 = kCCTexture2DPixelFormat_RGBA8888, + kTexture2DPixelFormat_RGB888 = kCCTexture2DPixelFormat_RGB888, + kTexture2DPixelFormat_RGB565 = kCCTexture2DPixelFormat_RGB565, + kTexture2DPixelFormat_A8 = kCCTexture2DPixelFormat_A8, + kTexture2DPixelFormat_RGBA4444 = kCCTexture2DPixelFormat_RGBA4444, + kTexture2DPixelFormat_RGB5A1 = kCCTexture2DPixelFormat_RGB5A1, + kTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_Default + + } CCTexture2DPixelFormat; + + enum { + kCCUniformPMatrix, + kCCUniformMVMatrix, + kCCUniformMVPMatrix, + kCCUniformTime, + kCCUniformSinTime, + kCCUniformCosTime, + kCCUniformRandom01, + kCCUniformSampler, + + kCCUniform_MAX, + }; + + typedef enum { + /// sets a 2D projection (orthogonal projection) + kCCDirectorProjection2D, + + /// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500. + kCCDirectorProjection3D, + + /// it calls "updateProjection" on the projection delegate. + kCCDirectorProjectionCustom, + + /// Default projection is 3D projection + kCCDirectorProjectionDefault = kCCDirectorProjection3D, + } ccDirectorProjection; + + typedef enum { + // CC_GL_SCISSOR_TEST = 1 << 0, + // CC_GL_STENCIL_TEST = 1 << 1, + // CC_GL_DEPTH_TEST = 1 << 2, + // CC_GL_BLEND = 1 << 3, + // CC_GL_DITHER = 1 << 4, + + // CC_GL_ALL = ( CC_GL_SCISSOR_TEST | CC_GL_STENCIL_TEST | CC_GL_DEPTH_TEST | CC_GL_BLEND | CC_GL_DITHER ), + // CC_GL_ALL = ( CC_GL_BLEND ), + CC_GL_ALL = 0, + + } ccGLServerState; + + enum ccScriptType { + kScriptTypeNone = 0, + kScriptTypeLua, + kScriptTypeJavascript + }; + + typedef enum + { + // this one might not actually exist in gd itself + KEY_Unknown = -0x01, + KEY_None = 0x00, + KEY_Backspace = 0x08, + KEY_Tab = 0x09, + KEY_Clear = 0x0C, + KEY_Enter = 0x0D, + KEY_Shift = 0x10, + KEY_Control = 0x11, + KEY_Alt = 0x12, + KEY_Pause = 0x13, + KEY_CapsLock = 0x14, + KEY_Escape = 0x1B, + KEY_Space = 0x20, + KEY_PageUp = 0x21, + KEY_PageDown = 0x22, + KEY_End = 0x23, + KEY_Home = 0x24, + KEY_Left = 0x25, + KEY_Up = 0x26, + KEY_Right = 0x27, + KEY_Down = 0x28, + KEY_Select = 0x29, + KEY_Print = 0x2A, + KEY_Execute = 0x2B, + KEY_PrintScreen = 0x2C, + KEY_Insert = 0x2D, + KEY_Delete = 0x2E, + KEY_Help = 0x2F, + KEY_Zero = 0x30, + KEY_One = 0x31, + KEY_Two = 0x32, + KEY_Three = 0x33, + KEY_Four = 0x34, + KEY_Five = 0x35, + KEY_Six = 0x36, + KEY_Seven = 0x37, + KEY_Eight = 0x38, + KEY_Nine = 0x39, + KEY_A = 0x41, + KEY_B = 0x42, + KEY_C = 0x43, + KEY_D = 0x44, + KEY_E = 0x45, + KEY_F = 0x46, + KEY_G = 0x47, + KEY_H = 0x48, + KEY_I = 0x49, + KEY_J = 0x4A, + KEY_K = 0x4B, + KEY_L = 0x4C, + KEY_M = 0x4D, + KEY_N = 0x4E, + KEY_O = 0x4F, + KEY_P = 0x50, + KEY_Q = 0x51, + KEY_R = 0x52, + KEY_S = 0x53, + KEY_T = 0x54, + KEY_U = 0x55, + KEY_V = 0x56, + KEY_W = 0x57, + KEY_X = 0x58, + KEY_Y = 0x59, + KEY_Z = 0x5A, + KEY_LeftWindowsKey = 0x5B, + KEY_RightWindowsKey = 0x5C, + KEY_ApplicationsKey = 0x5D, + KEY_Sleep = 0x5F, + KEY_NumPad0 = 0x60, + KEY_NumPad1 = 0x61, + KEY_NumPad2 = 0x62, + KEY_NumPad3 = 0x63, + KEY_NumPad4 = 0x64, + KEY_NumPad5 = 0x65, + KEY_NumPad6 = 0x66, + KEY_NumPad7 = 0x67, + KEY_NumPad8 = 0x68, + KEY_NumPad9 = 0x69, + KEY_Multiply = 0x6A, + KEY_Add = 0x6B, + KEY_Seperator = 0x6C, + KEY_Subtract = 0x6D, + KEY_Decimal = 0x6E, + KEY_Divide = 0x6F, + KEY_F1 = 0x70, + KEY_F2 = 0x71, + KEY_F3 = 0x72, + KEY_F4 = 0x73, + KEY_F5 = 0x74, + KEY_F6 = 0x75, + KEY_F7 = 0x76, + KEY_F8 = 0x77, + KEY_F9 = 0x78, + KEY_F10 = 0x79, + KEY_F11 = 0x7A, + KEY_F12 = 0x7B, + KEY_F13 = 0x7C, + KEY_F14 = 0x7D, + KEY_F15 = 0x7E, + KEY_F16 = 0x7F, + KEY_F17 = 0x80, + KEY_F18 = 0x81, + KEY_F19 = 0x82, + KEY_F20 = 0x83, + KEY_F21 = 0x84, + KEY_F22 = 0x85, + KEY_F23 = 0x86, + KEY_F24 = 0x87, + KEY_Numlock = 0x90, + KEY_ScrollLock = 0x91, + KEY_LeftShift = 0xA0, + KEY_RightShift = 0xA1, + KEY_LeftControl = 0xA2, + KEY_RightContol = 0xA3, + KEY_LeftMenu = 0xA4, + KEY_RightMenu = 0xA5, + KEY_BrowserBack = 0xA6, + KEY_BrowserForward = 0xA7, + KEY_BrowserRefresh = 0xA8, + KEY_BrowserStop = 0xA9, + KEY_BrowserSearch = 0xAA, + KEY_BrowserFavorites = 0xAB, + KEY_BrowserHome = 0xAC, + KEY_VolumeMute = 0xAD, + KEY_VolumeDown = 0xAE, + KEY_VolumeUp = 0xAF, + KEY_NextTrack = 0xB0, + KEY_PreviousTrack = 0xB1, + KEY_StopMedia = 0xB2, + KEY_PlayPause = 0xB3, + KEY_LaunchMail = 0xB4, + KEY_SelectMedia = 0xB5, + KEY_LaunchApp1 = 0xB6, + KEY_LaunchApp2 = 0xB7, + KEY_OEM1 = 0xBA, + KEY_OEMPlus = 0xB8, + KEY_OEMComma = 0xBC, + KEY_OEMMinus = 0xBD, + KEY_OEMPeriod = 0xBE, + KEY_OEM2 = 0xBF, + KEY_OEM3 = 0xC0, + KEY_OEM4 = 0xDB, + KEY_OEM5 = 0xDC, + KEY_OEM6 = 0xDD, + KEY_OEM7 = 0xDE, + KEY_OEM8 = 0xDF, + KEY_OEM102 = 0xE2, + KEY_Process = 0xE5, + KEY_Packet = 0xE7, + KEY_Attn = 0xF6, + KEY_CrSel = 0xF7, + KEY_ExSel = 0xF8, + KEY_EraseEOF = 0xF9, + KEY_Play = 0xFA, + KEY_Zoom = 0xFB, + KEY_PA1 = 0xFD, + KEY_OEMClear = 0xFE, + KEY_ArrowUp = 0x11B, + KEY_ArrowDown = 0x11C, + KEY_ArrowLeft = 0x11D, + KEY_ArrowRight = 0x11E, + CONTROLLER_A = 0x3E9, + CONTROLLER_B = 0x3EB, + CONTROLLER_Y = 0x3ED, + CONTROLLER_X = 0x3EF, + CONTROLLER_Start = 0x3F1, + CONTROLLER_Back = 0x3F3, + CONTROLLER_RB = 0x3F5, + CONTROLLER_LB = 0x3F7, + CONTROLLER_RT = 0x3F9, + CONTROLLER_LT = 0x3FB, + CONTROLLER_Up = 0x3FD, + CONTROLLER_Down = 0x3FF, + CONTROLLER_Left = 0x401, + CONTROLLER_Right = 0x403, + CONTROLLER_LTHUMBSTICK_UP = 0x405, + CONTROLLER_LTHUMBSTICK_DOWN = 0x407, + CONTROLLER_LTHUMBSTICK_LEFT = 0x409, + CONTROLLER_LTHUMBSTICK_RIGHT = 0x40B, + CONTROLLER_RTHUMBSTICK_UP = 0x40D, + CONTROLLER_RTHUMBSTICK_DOWN = 0x40F, + CONTROLLER_RTHUMBSTICK_LEFT = 0x411, + CONTROLLER_RTHUMBSTICK_RIGHT = 0x413, + } enumKeyCodes; + + typedef enum { + kCCTouchesAllAtOnce, + kCCTouchesOneByOne, + } ccTouchesMode; + + typedef enum + { + kCCTextAlignmentLeft, + kCCTextAlignmentCenter, + kCCTextAlignmentRight, + } CCTextAlignment; + + typedef enum + { + kCCVerticalTextAlignmentTop, + kCCVerticalTextAlignmentCenter, + kCCVerticalTextAlignmentBottom, + } CCVerticalTextAlignment; + + typedef enum eImageFormat + { + kCCImageFormatJPEG = 0, + kCCImageFormatPNG = 1, + } tCCImageFormat; + + typedef enum { + /** Living particles are attached to the world and are unaffected by emitter repositioning. */ + kCCPositionTypeFree, + + /** Living particles are attached to the world but will follow the emitter repositioning. + Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite. + */ + kCCPositionTypeRelative, + + /** Living particles are attached to the emitter and are translated along with it. */ + kCCPositionTypeGrouped, + } tCCPositionType; + + typedef enum + { + kCCMenuStateWaiting, + kCCMenuStateTrackingTouch + } tCCMenuState; + + RT_ADD( + typedef enum { + kTextureQualityLow = 1, + kTextureQualityMedium, + kTextureQualityHigh + } TextureQuality; + + typedef enum { + kPopTransitionFade, + kPopTransitionMoveInT + } PopTransition; + ) + + + // structs + struct _listEntry; + struct _hashUniformEntry; + struct _hashUpdateEntry; + struct _hashSelectorEntry; + struct _hashElement; + + typedef struct _ccBlendFunc + { + //! source blend function + GLenum src; + //! destination blend function + GLenum dst; + } ccBlendFunc; + + typedef struct _ccFontShadow + { + public: + + // shadow is not enabled by default + _ccFontShadow(): m_shadowEnabled(false) {} + + // true if shadow enabled + bool m_shadowEnabled; + // shadow x and y offset + cocos2d::CCSize m_shadowOffset; + // shadow blurrines + float m_shadowBlur; + // shadow opacity + float m_shadowOpacity; + } ccFontShadow; + + typedef struct _ccFontStroke + { + public: + + // stroke is disabled by default + _ccFontStroke(): m_strokeEnabled(false) {} + + // true if stroke enabled + bool m_strokeEnabled; + // stroke color + cocos2d::ccColor3B m_strokeColor; + // stroke size + float m_strokeSize; + } ccFontStroke; + + typedef struct _ccFontDefinition + { + public: + _ccFontDefinition(): + m_alignment(cocos2d::kCCTextAlignmentCenter), + m_vertAlignment(cocos2d::kCCVerticalTextAlignmentTop), + m_fontFillColor(cocos2d::ccWHITE), + m_dimensions(CCSizeMake(0, 0)) + {} + + // font name + std::string m_fontName; + // font size + int m_fontSize; + // horizontal alignment + cocos2d::CCTextAlignment m_alignment; + // vertical alignment + cocos2d::CCVerticalTextAlignment m_vertAlignment; + // renering box + cocos2d::CCSize m_dimensions; + // font color + cocos2d::ccColor3B m_fontFillColor; + // font shadow + ccFontShadow m_shadow; + // font stroke + ccFontStroke m_stroke; + + } ccFontDefinition; + + typedef struct _ccTexParams { + GLuint minFilter; + GLuint magFilter; + GLuint wrapS; + GLuint wrapT; + } ccTexParams; + + typedef struct _ccTex2F { + GLfloat u; + GLfloat v; + } ccTex2F; + + typedef struct _ccVertex2F + { + GLfloat x; + GLfloat y; + } ccVertex2F; + + typedef struct _ccVertex3F + { + GLfloat x; + GLfloat y; + GLfloat z; + } ccVertex3F; + + typedef struct _ccColor4F { + GLfloat r; + GLfloat g; + GLfloat b; + GLfloat a; + } ccColor4F; + + typedef struct _ccColor4B + { + GLubyte r; + GLubyte g; + GLubyte b; + GLubyte a; + } ccColor4B; + + typedef struct _ccHSVValue + { + float h, s, v; + bool absoluteSaturation; + bool absoluteBrightness; + private: unsigned char __pad[2]; + } ccHSVValue; + + typedef struct sCCParticle { + CCPoint pos; + CCPoint startPos; + + ccColor4F color; + ccColor4F deltaColor; + + float size; + float deltaSize; + + float rotation; + float deltaRotation; + + float timeToLive; + + unsigned int atlasIndex; + + //! Mode A: gravity, direction, radial accel, tangential accel + struct { + CCPoint dir; + float radialAccel; + float tangentialAccel; + } modeA; + + //! Mode B: radius mode + struct { + float angle; + float degreesPerSecond; + float radius; + float deltaRadius; + } modeB; + + } tCCParticle; + + typedef struct _ccV2F_C4B_T2F + { + //! vertices (2F) + ccVertex2F vertices; + //! colors (4B) + ccColor4B colors; + //! tex coords (2F) + ccTex2F texCoords; + } ccV2F_C4B_T2F; + + typedef struct _ccV3F_C4B_T2F + { + //! vertices (3F) + ccVertex3F vertices; // 12 bytes + // char __padding__[4]; + + //! colors (4B) + ccColor4B colors; // 4 bytes + // char __padding2__[4]; + + // tex coords (2F) + ccTex2F texCoords; // 8 bytes + } ccV3F_C4B_T2F; + + typedef struct _ccV3F_C4B_T2F_Quad + { + //! top left + ccV3F_C4B_T2F tl; + //! bottom left + ccV3F_C4B_T2F bl; + //! top right + ccV3F_C4B_T2F tr; + //! bottom right + ccV3F_C4B_T2F br; + } ccV3F_C4B_T2F_Quad; + + typedef enum LanguageType + { + kLanguageEnglish = 0, + kLanguageChinese, + kLanguageFrench, + kLanguageItalian, + kLanguageGerman, + kLanguageSpanish, + kLanguageDutch, + kLanguageRussian, + kLanguageKorean, + kLanguageJapanese, + kLanguageHungarian, + kLanguagePortuguese, + kLanguageArabic + } ccLanguageType; + + enum TargetPlatform + { + kTargetWindows, + kTargetLinux, + kTargetMacOS, + kTargetAndroid, + kTargetIphone, + kTargetIpad, + kTargetBlackBerry, + kTargetNaCl, + kTargetEmscripten, + kTargetTizen, + kTargetWinRT, + kTargetWP8 + }; + + enum ccTouchType { + CCTOUCHBEGAN = 0, + CCTOUCHMOVED = 1, + CCTOUCHENDED = 2, + CCTOUCHCANCELLED = 3, + + ccTouchMax = 4, + }; + + + struct cc_timeval + { + #ifdef __native_client__ + time_t tv_sec; // seconds + #else + long tv_sec; // seconds + #endif + int tv_usec; // microSeconds + }; + + typedef struct _BMFontPadding { + /// padding left + int left; + /// padding top + int top; + /// padding right + int right; + /// padding bottom + int bottom; + } ccBMFontPadding; + + typedef struct _BMFontDef { + //! ID of the character + unsigned int charID; + //! origin and size of the font + CCRect rect; + //! The X amount the image should be offset when drawing the image (in pixels) + short xOffset; + //! The Y amount the image should be offset when drawing the image (in pixels) + short yOffset; + //! The amount to move the current position after drawing the character (in pixels) + short xAdvance; + } ccBMFontDef; + + typedef struct _FontDefHashElement + { + unsigned int key; // key. Font Unicode value + ccBMFontDef fontDef; // font definition + UT_hash_handle hh; + } tCCFontDefHashElement; + + typedef struct _KerningHashElement + { + int key; // key for the hash. 16-bit for 1st element, 16-bit for 2nd element + int amount; + UT_hash_handle hh; + } tCCKerningHashElement; + + typedef struct + { + CCRect begin; // the soft keyboard rectangle when animation begins + CCRect end; // the soft keyboard rectangle when animation ends + float duration; // the soft keyboard animation duration + } CCIMEKeyboardNotificationInfo; + + struct ccTouchHandlerHelperData { + // we only use the type + // void (StandardTouchDelegate::*touchesSel)(CCSet*, CCEvent*); + // void (TargetedTouchDelegate::*touchSel)(NSTouch*, CCEvent*); + int m_type; + }; + + // 2.2 additions + struct ParticleStruct { + + }; + + + // CCObject + class CCObject; + class CCZone; + class CCAutoreleasePool; + class CCArray; + class CCNode; + class CCEvent; + typedef struct _ccArray { + unsigned int num, max; + // 2.2 additions + unsigned int unknown; + CCObject** arr; + } ccArray; + typedef struct _ccCArray { + unsigned int num, max; + void** arr; + } ccCArray; + + /* typedefs */ + typedef void (CCObject::*SEL_SCHEDULE)(float); + typedef void (CCObject::*SEL_CallFunc)(); + typedef void (CCObject::*SEL_CallFuncN)(CCNode*); + typedef void (CCObject::*SEL_CallFuncND)(CCNode*, void*); + typedef void (CCObject::*SEL_CallFuncO)(CCObject*); + typedef void (CCObject::*SEL_MenuHandler)(CCObject*); + typedef void (CCObject::*SEL_EventHandler)(CCEvent*); + typedef int (CCObject::*SEL_Compare)(CCObject*); + + class CCCopying + { + public: + virtual CCObject* copyWithZone(CCZone* pZone) { return 0; } + }; + + class CCBool; + class CCInteger; + class CCFloat; + class CCDouble; + class CCString; + class CCDictionary; + class CCSet; + class CCDataVisitor + { + public: + virtual ~CCDataVisitor() {} + + /** default method, called from non-overloaded methods and for unrecognized objects */ + virtual void visitObject(const CCObject *p) = 0; + + virtual void visit(const CCBool *p); + virtual void visit(const CCInteger *p); + virtual void visit(const CCFloat *p); + virtual void visit(const CCDouble *p); + virtual void visit(const CCString *p); + virtual void visit(const CCArray *p); + virtual void visit(const CCDictionary *p); + virtual void visit(const CCSet *p); + }; + + class CCObject + { + public: + unsigned int m_uID; + int m_nLuaID; + protected: + int m_nTag; + unsigned int m_uReference; + // count of autorelease + unsigned int m_uAutoReleaseCount; + + CCObjectType m_eObjType; + + int m_uIndexInArray; + + // 2.2 additions + + int m_uUnknown; + int m_unknown2; + int m_nZOrder; + int m_uOrderOfArrival; + int m_unknown5; + + public: + CCObject(void); + virtual ~CCObject(void); + + void release(void); + void retain(void); + CCObject* autorelease(void); + CCObject* copy(void); + bool isSingleReference(void) const; + inline unsigned int retainCount(void) const { + return m_uReference; + } + virtual bool isEqual(const CCObject* pObject); + + virtual void acceptVisitor(CCDataVisitor &visitor); + + virtual void update(float dt) {CC_UNUSED_PARAM(dt);}; + + virtual void encodeWithCoder(DS_Dictionary*); + + static CCObject* createWithCoder(DS_Dictionary*); + + virtual bool canEncode(); + + inline CCObjectType getObjType() const { + return m_eObjType; + } + + virtual int getTag() const; + + virtual void setTag(int nTag); + + inline void setObjType(CCObjectType type) { + m_eObjType = type; + } + + friend class CCAutoreleasePool; + }; + + class CCBool : public CCObject + { + public: + CCBool(bool v) + : m_bValue(v) {} + bool getValue() const {return m_bValue;} + bool setValue(bool value) { m_bValue = value; return value; } + + static CCBool* create(bool v) + { + CCBool* pRet = new CCBool(v); + if (pRet) + { + pRet->autorelease(); + } + return pRet; + } + + virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); } + + private: + bool m_bValue; + }; + class CCInteger : public CCObject + { + public: + CCInteger(int v) + : m_nValue(v) {} + int getValue() const {return m_nValue;} + void setValue(int v) { m_nValue = v; }; + + static CCInteger* create(int v) + { + CCInteger* pRet = new CCInteger(v); + pRet->autorelease(); + return pRet; + } + + virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); } + + private: + int m_nValue; + }; + class CCFloat : public CCObject + { + public: + CCFloat(float v) + : m_fValue(v) {} + float getValue() const {return m_fValue;} + + static CCFloat* create(float v) + { + CCFloat* pRet = new CCFloat(v); + if (pRet) + { + pRet->autorelease(); + } + return pRet; + } + + virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); } + + private: + float m_fValue; + }; + class CCDouble : public CCObject + { + public: + CCDouble(double v) + : m_dValue(v) {} + double getValue() const {return m_dValue;} + + static CCDouble* create(double v) + { + CCDouble* pRet = new CCDouble(v); + if (pRet) + { + pRet->autorelease(); + } + return pRet; + } + + virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); } + + private: + double m_dValue; + }; + #define kMaxStringLen (1024*100) + class CCString : public CCObject + { + public: + inline CCString(const char* str) : m_sString(str) {} + inline CCString(const std::string& str) : m_sString(str.c_str()) {} + inline CCString(const CCString& str) {} + virtual inline ~CCString() {} + + CCString& operator= (const CCString& other); + + bool initWithFormat(const char* format, ...) CC_FORMAT_PRINTF(2, 3); + + int intValue() const; + + unsigned int uintValue() const; + + float floatValue() const; + + double doubleValue() const; + + bool boolValue() const; + + const char* getCString() const; + + unsigned int length() const; + + int compare(const char *) const; + + virtual CCObject* copyWithZone(CCZone* pZone); + virtual bool isEqual(const CCObject* pObject); + + static CCString* createWithData(const unsigned char* pData, unsigned long nLen); + + static CCString* createWithContentsOfFile(const char* pszFileName); + virtual void acceptVisitor(CCDataVisitor &visitor); + + private: + + bool initWithFormatAndValist(const char* format, va_list ap) { + bool bRet = false; + char* pBuf = (char*)malloc(kMaxStringLen); + if (pBuf != NULL) + { + vsnprintf(pBuf, kMaxStringLen, format, ap); + m_sString = pBuf; + free(pBuf); + bRet = true; + } + return bRet; + } + + public: + std::string m_sString; + }; + typedef std::set::iterator CCSetIterator; + class CCSet : public CCObject + { + public: + CCSet(void); + // CCSet(const CCSet &rSetObject); + virtual ~CCSet(void); + + static CCSet * create(); + + CCSet* copy(); + CCSet* mutableCopy(); + int count(); + void addObject(CCObject *pObject); + void removeObject(CCObject *pObject); + void removeAllObjects(); + bool containsObject(CCObject *pObject); + CCSetIterator begin(); + CCSetIterator end(); + CCObject* anyObject(); + virtual void acceptVisitor(CCDataVisitor &visitor); + + private: + std::set *m_pSet; + }; + + + // CCArray + class CCAutoreleasePool : public CCObject + { + private: + CCArray* m_pManagedObjectArray; + }; + + class CCPoolManager + { + private: + CCArray* m_pReleasePoolStack; + CCAutoreleasePool* m_pCurReleasePool; + + private: + friend class CCAutoreleasePool; + }; + + class CCArray : public CCObject + { + public: + ~CCArray(); + + static CCArray* create(); + static CCArray* create(CCObject* pObject, ...); + static CCArray* createWithObject(CCObject* pObject); + static CCArray* createWithCapacity(unsigned int capacity); + static CCArray* createWithArray(CCArray* otherArray); + static CCArray* createWithContentsOfFile(const char* pFileName); + + static CCArray* createWithContentsOfFileThreadSafe(const char* pFileName); + + bool init(); + bool initWithObject(CCObject* pObject); + bool initWithObjects(CCObject* pObject, ...); + bool initWithCapacity(unsigned int capacity); + bool initWithArray(CCArray* otherArray); + + unsigned int count() const; + unsigned int capacity() const; + unsigned int indexOfObject(CCObject* object) const; + CCObject* objectAtIndex(unsigned int index); + CCString* stringAtIndex(unsigned int index); + + CCObject* firstObject(); + CCObject* lastObject(); + CCObject* randomObject(); + bool containsObject(CCObject* object) const; + bool isEqualToArray(CCArray* pOtherArray); + + void addObject(CCObject* object); + + void addObjectNew(CCObject* object); + void addObjectsFromArray(CCArray* otherArray); + void insertObject(CCObject* object, unsigned int index); + + void removeFirstObject(bool bReleaseObj = true); + void removeLastObject(bool bReleaseObj = true); + void removeObject(CCObject* object, bool bReleaseObj = true); + void removeObjectAtIndex(unsigned int index, bool bReleaseObj = true); + void removeObjectsInArray(CCArray* otherArray); + void removeAllObjects(); + void fastRemoveObject(CCObject* object); + void fastRemoveObjectAtIndex(unsigned int index); + void fastRemoveObjectAtIndexNew(unsigned int index); + + void fastRemoveObjectAtIndexChild(unsigned int); + + void recreateNewIndexes(); + void removeObjectAtIndexChild(unsigned int, bool); + + void exchangeObject(CCObject* object1, CCObject* object2); + void exchangeObjectAtIndex(unsigned int index1, unsigned int index2); + + void replaceObjectAtIndex(unsigned int uIndex, CCObject* pObject, bool bReleaseObject = true); + + void reverseObjects(); + void reduceMemoryFootprint(); + + virtual CCObject* copyWithZone(CCZone* pZone); + + virtual void acceptVisitor(CCDataVisitor &visitor); + + public: + ccArray* data; + }; + + + // CCDictionary + class CCDictElement + { + private: + CCDictElement(const char* pszKey, CCObject* pObject); + CCDictElement(intptr_t iKey, CCObject* pObject); + + public: + ~CCDictElement(); + + inline const char* getStrKey() const + { + CCAssert(m_szKey[0] != '\0', "Should not call this function for integer dictionary"); + return m_szKey; + } + + inline intptr_t getIntKey() const + { + CCAssert(m_szKey[0] == '\0', "Should not call this function for string dictionary"); + return m_iKey; + } + + inline CCObject* getObject() const { return m_pObject; } + + private: + // The max length of string key. + #define MAX_KEY_LEN 256 + // char array is needed for HASH_ADD_STR in UT_HASH. + // So it's a pain that all elements will allocate 256 bytes for this array. + char m_szKey[MAX_KEY_LEN]; // hash key of string type + intptr_t m_iKey; // hash key of integer type + CCObject* m_pObject; // hash value + public: + UT_hash_handle hh; // makes this class hashable + friend class CCDictionary; // declare CCDictionary as friend class + }; + + class CCDictionary : public CCObject + { + public: + CCDictionary(); + ~CCDictionary(); + + unsigned int count(); + + CCArray* allKeys(); + + CCArray* allKeysForObject(CCObject* object); + + CCObject* objectForKey(const std::string& key); + + CCObject* objectForKey(intptr_t key); + + const CCString* valueForKey(const std::string& key); + + const CCString* valueForKey(intptr_t key); + + void setObject(CCObject* pObject, const std::string& key); + + void setObject(CCObject* pObject, intptr_t key); + + void removeObjectForKey(const std::string& key); + + void removeObjectForKey(intptr_t key); + + void removeObjectsForKeys(CCArray* pKeyArray); + + void removeObjectForElememt(CCDictElement* pElement); + + void removeAllObjects(); + + virtual CCObject* copyWithZone(CCZone* pZone); + + CCObject* randomObject(); + + static CCDictionary* create(); + + static CCDictionary* createWithDictionary(CCDictionary* srcDict); + + static CCDictionary* createWithContentsOfFile(const char *pFileName); + + bool writeToFile(const char *fullPath); + + static CCDictionary* createWithContentsOfFileThreadSafe(const char *pFileName); + + virtual void acceptVisitor(CCDataVisitor &visitor); + + char const* charForKey(std::string const&); + std::string getFirstKey(); + + private: + void setObjectUnSafe(CCObject* pObject, const std::string& key); + void setObjectUnSafe(CCObject* pObject, const intptr_t key); + + public: + CCDictElement* m_pElements; + + enum CCDictType + { + kCCDictUnknown = 0, + kCCDictStr, + kCCDictInt + }; + + CCDictType m_eDictType; + }; + + + // CCNode + struct CCAffineTransform { + float a, b, c, d; + float tx, ty; + }; + + class CCCamera : public CCObject + { + protected: + float m_fEyeX; + float m_fEyeY; + float m_fEyeZ; + + float m_fCenterX; + float m_fCenterY; + float m_fCenterZ; + + float m_fUpX; + float m_fUpY; + float m_fUpZ; + + bool m_bDirty; + kmMat4 m_lookupMatrix; + public: + CCCamera(void); + ~CCCamera(void); + + void init(void); + const char* description(void); + + inline void setDirty(bool bValue) { m_bDirty = bValue; } + inline bool isDirty(void) { return m_bDirty; } + + void restore(void); + void locate(void); + void setEyeXYZ(float fEyeX, float fEyeY, float fEyeZ); + void setCenterXYZ(float fCenterX, float fCenterY, float fCenterZ); + void setUpXYZ(float fUpX, float fUpY, float fUpZ); + + void getEyeXYZ(float *pEyeX, float *pEyeY, float *pEyeZ); + void getCenterXYZ(float *pCenterX, float *pCenterY, float *pCenterZ); + void getUpXYZ(float *pUpX, float *pUpY, float *pUpZ); + public: + static float getZEye(); + }; + + class CCGLProgram : CCObject + { + public: + CCGLProgram(); + virtual ~CCGLProgram(); + + protected: + GLuint m_uProgram; + GLuint m_uVertShader; + GLuint m_uFragShader; + GLint m_uUniforms[kCCUniform_MAX]; + struct _hashUniformEntry* m_pHashForUniforms; + bool m_bUsesTime; + bool m_hasShaderCompiler; + + #if 0 // windows phone my beloved + #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + std::string m_shaderId; + #endif + #endif + }; + + class CCImage : public CCObject + { + public: + CC_SYNTHESIZE_READONLY_NV(unsigned short, m_nWidth, Width); + CC_SYNTHESIZE_READONLY_NV(unsigned short, m_nHeight, Height); + CC_SYNTHESIZE_READONLY_NV(int, m_nBitsPerComponent, BitsPerComponent); + + protected: + unsigned char *m_pData; + bool m_bHasAlpha; + bool m_bPreMulti; + + #if 0 + #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) + CCFreeTypeFont* m_ft; + #endif + #endif + }; + + class CCTexture2D : public CCObject + { + public: + CCTexture2D(); + virtual ~CCTexture2D(); + const char* description(void); + + void releaseData(void *data); + void* keepData(void *data, unsigned int length); + + bool initWithData(const void* data, CCTexture2DPixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const CCSize& contentSize); + + void drawAtPoint(const CCPoint& point); + void drawInRect(const CCRect& rect); + + bool initWithString(const char *text, const char *fontName, float fontSize, const CCSize& dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment); + bool initWithString(const char *text, const char *fontName, float fontSize); + bool initWithString(const char *text, ccFontDefinition *textDefinition); + + bool initWithPVRFile(const char* file); + + bool initWithETCFile(const char* file); + + void setTexParameters(ccTexParams* texParams); + + void setAntiAliasTexParameters(); + + void setAliasTexParameters(); + + + void generateMipmap(); + + const char* stringForFormat(); + + unsigned int bitsPerPixelForFormat(); + + unsigned int bitsPerPixelForFormat(CCTexture2DPixelFormat format); + + static void setDefaultAlphaPixelFormat(CCTexture2DPixelFormat format); + + static CCTexture2DPixelFormat defaultAlphaPixelFormat(); + + static void PVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied); + + const CCSize& getContentSizeInPixels(); + + bool hasPremultipliedAlpha(); + bool hasMipmaps(); + + void releaseGLTexture(); + + private: + bool initPremultipliedATextureWithImage(CCImage * image, unsigned int pixelsWide, unsigned int pixelsHigh); + + // By default PVR images are treated as if they don't have the alpha channel premultiplied + bool m_bPVRHaveAlphaPremultiplied; + + /** pixel format of the texture */ + CC_PROPERTY_READONLY(CCTexture2DPixelFormat, m_ePixelFormat, PixelFormat) + /** width in pixels */ + CC_PROPERTY_READONLY(unsigned int, m_uPixelsWide, PixelsWide) + /** height in pixels */ + CC_PROPERTY_READONLY(unsigned int, m_uPixelsHigh, PixelsHigh) + + /** texture name */ + CC_PROPERTY_READONLY(GLuint, m_uName, Name) + + /** texture max S */ + CC_PROPERTY(GLfloat, m_fMaxS, MaxS) + /** texture max T */ + CC_PROPERTY(GLfloat, m_fMaxT, MaxT) + /** content size */ + CC_PROPERTY_READONLY(CCSize, m_tContentSize, ContentSize) + + /** whether or not the texture has their Alpha premultiplied */ + bool m_bHasPremultipliedAlpha; + + bool m_bHasMipmaps; + + /** shader program used by drawAtPoint and drawInRect */ + CC_PROPERTY(CCGLProgram*, m_pShaderProgram, ShaderProgram); + }; + + class CCGrabber : public CCObject + { + protected: + GLuint m_FBO; + GLint m_oldFBO; + GLfloat m_oldClearColor[4]; + }; + + class CCGridBase : public CCObject + { + public: + virtual ~CCGridBase(void); + + inline bool isActive(void) { return m_bActive; } + void setActive(bool bActive); + + inline int getReuseGrid(void) { return m_nReuseGrid; } + inline void setReuseGrid(int nReuseGrid) { m_nReuseGrid = nReuseGrid; } + + inline const CCSize& getGridSize(void) { return m_sGridSize; } + inline void setGridSize(const CCSize& gridSize) { m_sGridSize = gridSize; } + + inline const CCPoint& getStep(void) { return m_obStep; } + inline void setStep(const CCPoint& step) { m_obStep = step; } + + inline bool isTextureFlipped(void) { return m_bIsTextureFlipped; } + void setTextureFlipped(bool bFlipped); + bool initWithSize(const CCSize& gridSize, CCTexture2D *pTexture, bool bFlipped); + bool initWithSize(const CCSize& gridSize); + void beforeDraw(void); + void afterDraw(CCNode *pTarget); + virtual void blit(void); + virtual void reuse(void); + virtual void calculateVertexPoints(void); + + public: + static CCGridBase* create(const CCSize& gridSize, CCTexture2D *texture, bool flipped); + static CCGridBase* create(const CCSize& gridSize); + void set2DProjection(void); + + protected: + bool m_bActive; + int m_nReuseGrid; + CCSize m_sGridSize; + CCTexture2D *m_pTexture; + CCPoint m_obStep; + CCGrabber *m_pGrabber; + bool m_bIsTextureFlipped; + CCGLProgram* m_pShaderProgram; + ccDirectorProjection m_directorProjection; + }; + + class CCScheduler : public CCObject + { + protected: + float m_fTimeScale; + + // + // "updates with priority" stuff + // + struct _listEntry *m_pUpdatesNegList; // list of priority < 0 + struct _listEntry *m_pUpdates0List; // list priority == 0 + struct _listEntry *m_pUpdatesPosList; // list priority > 0 + struct _hashUpdateEntry *m_pHashForUpdates; // hash used to fetch quickly the list entries for pause,delete,etc + + // Used for "selectors with interval" + struct _hashSelectorEntry *m_pHashForTimers; + struct _hashSelectorEntry *m_pCurrentTarget; + bool m_bCurrentTargetSalvaged; + // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. + bool m_bUpdateHashLocked; + CCArray* m_pScriptHandlerEntries; + }; + + class CCActionManager : public CCObject + { + protected: + struct _hashElement *m_pTargets; + struct _hashElement *m_pCurrentTarget; + bool m_bCurrentTargetSalvaged; + }; + + class CCComponent : public CCObject + { + protected: + CCComponent(void); + + public: + virtual ~CCComponent(void); + virtual bool init(); + virtual void onEnter(); + virtual void onExit(); + virtual void update(float delta); + virtual bool serialize(void* r); + virtual bool isEnabled() const; + virtual void setEnabled(bool b); + static CCComponent* create(void); + + const char* getName() const; + void setName(const char *pName); + + void setOwner(CCNode *pOwner); + CCNode* getOwner() const; + + protected: + CCNode *m_pOwner; + std::string m_strName; + bool m_bEnabled; + }; + + class CCComponentContainer + { + protected: + CCComponentContainer(CCNode *pNode); + + public: + virtual ~CCComponentContainer(void); + virtual CCComponent* get(const char *pName) const; + virtual bool add(CCComponent *pCom); + virtual bool remove(const char *pName); + virtual bool remove(CCComponent *pCom); + virtual void removeAll(); + virtual void visit(float fDelta); + public: + bool isEmpty() const; + + private: + void alloc(void); + + private: + CCDictionary *m_pComponents; ///< Dictionary of components + CCNode *m_pOwner; + + friend class CCNode; + }; + + class CCAction : public CCObject + { + public: + CCAction(void); + virtual ~CCAction(void); + const char* description(); + virtual CCObject* copyWithZone(CCZone *pZone); + + virtual bool isDone(void); + + virtual void startWithTarget(CCNode *pTarget); + + virtual void stop(void); + + virtual void step(float dt); + + virtual void update(float time); + + inline CCNode* getTarget(void) { return m_pTarget; } + inline void setTarget(CCNode *pTarget) { m_pTarget = pTarget; } + + inline CCNode* getOriginalTarget(void) { return m_pOriginalTarget; } + inline void setOriginalTarget(CCNode *pOriginalTarget) { m_pOriginalTarget = pOriginalTarget; } + + inline int getTag(void) { return m_nTag; } + inline void setTag(int nTag) { m_nTag = nTag; } + + RT_ADD(void setSpeedMod(float mod);) + + // 2.2 addition + float getSpeedMod(); + + public: + static CCAction* create(); + protected: + CCNode *m_pOriginalTarget; + CCNode *m_pTarget; + int m_nTag; + RT_ADD(float m_fSpeedMod;) + }; + + class CCTouch : public CCObject + { + public: + int m_nId; + bool m_startPointCaptured; + CCPoint m_startPoint; + CCPoint m_point; + CCPoint m_prevPoint; + }; + + class CCEvent : public CCObject + {}; + + class CCNode : public CCObject + { + public: + CCNode(void); + + virtual ~CCNode(void); + + virtual bool init(); + static CCNode * create(void); + + const char* description(void); + + virtual void setZOrder(int zOrder); + virtual void _setZOrder(int z); + virtual int getZOrder(); + + virtual void setVertexZ(float vertexZ); + virtual float getVertexZ(); + + virtual void setScaleX(float fScaleX); + virtual float getScaleX(); + + virtual void setScaleY(float fScaleY); + virtual float getScaleY(); + + virtual void setScale(float scale); + virtual float getScale(); + + virtual void setScale(float fScaleX,float fScaleY); + + virtual void setPosition(const CCPoint &position); + virtual const CCPoint& getPosition(); + virtual void setPosition(float x, float y); + virtual void getPosition(float* x, float* y); + virtual void setPositionX(float x); + virtual float getPositionX(void); + virtual void setPositionY(float y); + virtual float getPositionY(void); + + virtual void setSkewX(float fSkewX); + virtual float getSkewX(); + + virtual void setSkewY(float fSkewY); + virtual float getSkewY(); + + virtual void setAnchorPoint(const CCPoint& anchorPoint); + virtual const CCPoint& getAnchorPoint(); + virtual const CCPoint& getAnchorPointInPoints(); + + virtual void setContentSize(const CCSize& contentSize); + virtual const CCSize& getContentSize() const; + + RT_ADD(virtual CCSize getScaledContentSize(void); ) + + virtual void setVisible(bool visible); + virtual bool isVisible(); + + virtual void setRotation(float fRotation); + virtual float getRotation(); + + virtual void setRotationX(float fRotaionX); + virtual float getRotationX(); + + virtual void setRotationY(float fRotationY); + virtual float getRotationY(); + + virtual void setOrderOfArrival(unsigned int uOrderOfArrival); + virtual unsigned int getOrderOfArrival(); + + virtual void setGLServerState(ccGLServerState glServerState); + virtual ccGLServerState getGLServerState(); + + virtual void ignoreAnchorPointForPosition(bool ignore); + virtual bool isIgnoreAnchorPointForPosition(); + + virtual void addChild(CCNode * child); + virtual void addChild(CCNode * child, int zOrder); + virtual void addChild(CCNode* child, int zOrder, int tag); + virtual CCNode * getChildByTag(int tag); + virtual CCArray* getChildren(); + + virtual unsigned int getChildrenCount(void) const; + + virtual void setParent(CCNode* parent); + virtual CCNode* getParent(); + + virtual void removeFromParent(); + virtual void removeFromParentAndCleanup(bool cleanup); + + RT_ADD( virtual void removeMeAndCleanup(void); ) + + virtual void removeChild(CCNode* child); + virtual void removeChild(CCNode* child, bool cleanup); + virtual void removeChildByTag(int tag); + virtual void removeChildByTag(int tag, bool cleanup); + virtual void removeAllChildren(); + virtual void removeAllChildrenWithCleanup(bool cleanup); + + virtual void reorderChild(CCNode * child, int zOrder); + + virtual void sortAllChildren(); + + virtual CCGridBase* getGrid(); + virtual void setGrid(CCGridBase *pGrid); + + RT_REMOVE( virtual int getTag() const; ) + RT_REMOVE( virtual void setTag(int nTag); ) + + virtual void* getUserData(); + virtual void setUserData(void *pUserData); + + virtual CCObject* getUserObject(); + virtual void setUserObject(CCObject *pUserObject); + + public: + virtual CCCamera* getCamera(); + + virtual bool isRunning(); + virtual void registerScriptHandler(int handler); + virtual void unregisterScriptHandler(void); + inline int getScriptHandler() { return m_nScriptHandler; }; + + void scheduleUpdateWithPriorityLua(int nHandler, int priority); + + virtual void onEnter(); + + virtual void onEnterTransitionDidFinish(); + + virtual void onExit(); + + virtual void onExitTransitionDidStart(); + + virtual void cleanup(void); + + virtual void draw(void); + + virtual void visit(void); + + CCRect boundingBox(void); + + virtual void setActionManager(CCActionManager* actionManager); + virtual CCActionManager* getActionManager(); + + CCAction* runAction(CCAction* action); + + void stopAllActions(void); + + void stopAction(CCAction* action); + + void stopActionByTag(int tag); + + CCAction* getActionByTag(int tag); + + unsigned int numberOfRunningActions(void); + + virtual void setScheduler(CCScheduler* scheduler); + virtual CCScheduler* getScheduler(); + + bool isScheduled(SEL_SCHEDULE selector); + + void scheduleUpdate(void); + + void scheduleUpdateWithPriority(int priority); + + void unscheduleUpdate(void); + + void schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay); + + void schedule(SEL_SCHEDULE selector, float interval); + + void scheduleOnce(SEL_SCHEDULE selector, float delay); + + void schedule(SEL_SCHEDULE selector); + + void unschedule(SEL_SCHEDULE selector); + + void unscheduleAllSelectors(void); + + void resumeSchedulerAndActions(void); + void pauseSchedulerAndActions(void); + + virtual void update(float delta); + + void transform(void); + void transformAncestors(void); + virtual void updateTransform(void); + + RT_REMOVE( virtual CCAffineTransform nodeToParentTransform(void); ) + RT_ADD( virtual const CCAffineTransform nodeToParentTransform(void); ) + + // 2.2 additions + virtual const CCAffineTransform nodeToParentTransformFast(); + + RT_REMOVE( virtual CCAffineTransform parentToNodeTransform(void); ) + RT_ADD( virtual const CCAffineTransform parentToNodeTransform(void);) + + virtual CCAffineTransform nodeToWorldTransform(void); + + // 2.2 additions + virtual CCAffineTransform nodeToWorldTransformFast(); + + virtual CCAffineTransform worldToNodeTransform(void); + + CCPoint convertToNodeSpace(const CCPoint& worldPoint); + + CCPoint convertToWorldSpace(const CCPoint& nodePoint); + + CCPoint convertToNodeSpaceAR(const CCPoint& worldPoint); + + CCPoint convertToWorldSpaceAR(const CCPoint& nodePoint); + + CCPoint convertTouchToNodeSpace(CCTouch * touch); + + CCPoint convertTouchToNodeSpaceAR(CCTouch * touch); + + void setAdditionalTransform(const CCAffineTransform& additionalTransform); + + CCComponent* getComponent(const char *pName) const; + + virtual bool addComponent(CCComponent *pComponent); + + virtual bool removeComponent(const char *pName); + + virtual bool removeComponent(CCComponent *pComponent); + + virtual void removeAllComponents(); + + RT_ADD( + virtual void updateTweenAction(float, const char*); + + CCNode& operator=(const CCNode&); + ) + + virtual void updateTweenActionInt(float, int); + + cocos2d::CCAffineTransform getTransformTemp(); + + bool getUseChildIndex(); + void setUseChildIndex(bool); + void qsortAllChildrenWithIndex(); + + protected: + static void resetGlobalOrderOfArrival(); + + public: + void sortAllChildrenNoIndex(); + void sortAllChildrenWithIndex(); + void updateChildIndexes(); + + private: + void childrenAlloc(void); + void insertChild(CCNode* child, int z); + void detachChild(CCNode *child, bool doCleanup); + CCPoint convertToWindowSpace(const CCPoint& nodePoint); + + protected: + float m_fRotationX; + float m_fRotationY; + + float m_fScaleX; + float m_fScaleY; + + float m_fVertexZ; + + CCPoint m_obPosition; + + float m_fSkewX; + float m_fSkewY; + + CCPoint m_obAnchorPointInPoints; + CCPoint m_obAnchorPoint; + + CCSize m_obContentSize; + + + CCAffineTransform m_sAdditionalTransform; + CCAffineTransform m_sTransform; + CCAffineTransform m_sInverse; + + CCCamera *m_pCamera; + + CCGridBase *m_pGrid; + + // 2.2 additions + RT_REMOVE( int m_nZOrder; ) + + CCArray *m_pChildren; + CCNode *m_pParent; + + RT_REMOVE( int m_nTag; ) + + void *m_pUserData; + CCObject *m_pUserObject; + + CCGLProgram *m_pShaderProgram; + + ccGLServerState m_eGLServerState; + + // 2.2 additions + RT_REMOVE( unsigned int m_uOrderOfArrival; ) + + CCScheduler *m_pScheduler; + + CCActionManager *m_pActionManager; + + bool m_bRunning; + + bool m_bTransformDirty; + bool m_bInverseDirty; + bool m_bAdditionalTransformDirty; + + // 2.2 additions + PAD(10); + + bool m_bVisible; + + bool m_bIgnoreAnchorPointForPosition; + + bool m_bReorderChildDirty; + + int m_nScriptHandler; + int m_nUpdateScriptHandler; + ccScriptType m_eScriptType; + + CCComponentContainer *m_pComponentContainer; + + // 2.2 additions + bool m_bUnkBool1; + bool m_bUnkBool2; + }; + + + // CCLayer + class CCTouchDelegate + { + public: + + CCTouchDelegate() {} + + virtual ~CCTouchDelegate() {} + + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent); return false;}; + + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} + + virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent) {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + + virtual void setPreviousPriority(int); + virtual int getPreviousPriority(); + }; + + class CCAcceleration + { + public: + double x; + double y; + double z; + + double timestamp; + }; + + class CCAccelerometerDelegate + { + public: + CCAccelerometerDelegate() {} + + virtual void didAccelerate(CCAcceleration* pAccelerationValue) {CC_UNUSED_PARAM(pAccelerationValue);} + }; + + class CCKeypadDelegate + { + public: + virtual void keyBackClicked() {} + + virtual void keyMenuClicked() {}; + }; + + class CCKeyboardDelegate + { + public: + virtual void keyDown(enumKeyCodes key) {} + + virtual void keyUp(enumKeyCodes key) {} + }; + + RT_ADD( + class CCMouseDelegate + { + public: + virtual void rightKeyDown() {} + + virtual void rightKeyUp() {} + + virtual void scrollWheel(float x, float y) {} + }; + ) + + class CCScriptHandlerEntry : public CCObject + { + protected: + + int m_nHandler; + int m_nEntryId; + }; + + class CCTouchScriptHandlerEntry : public CCScriptHandlerEntry + { + private: + bool m_bIsMultiTouches; + int m_nPriority; + bool m_bSwallowsTouches; + }; + + class CCLayer : public CCNode, public CCTouchDelegate, public CCAccelerometerDelegate, public CCKeypadDelegate + RT_ADD(, public CCKeyboardDelegate, public CCMouseDelegate) + { + public: + CCLayer(); + virtual ~CCLayer(); + virtual bool init(); + + static CCLayer *create(void); + virtual void onEnter(); + virtual void onExit(); + virtual void onEnterTransitionDidFinish(); + + virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); + virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); + + virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent); + virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent); + virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent); + virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent); + virtual void didAccelerate(CCAcceleration* pAccelerationValue); + void registerScriptAccelerateHandler(int nHandler); + void unregisterScriptAccelerateHandler(void); + + virtual void registerWithTouchDispatcher(void); + + virtual void registerScriptTouchHandler(int nHandler, bool bIsMultiTouches = false, int nPriority = INT_MIN, bool bSwallowsTouches = false); + virtual void unregisterScriptTouchHandler(void); + + virtual bool isTouchEnabled(); + virtual void setTouchEnabled(bool value); + + virtual void setTouchMode(ccTouchesMode mode); + virtual int getTouchMode(); + + virtual void setTouchPriority(int priority); + virtual int getTouchPriority(); + + virtual bool isAccelerometerEnabled(); + virtual void setAccelerometerEnabled(bool value); + virtual void setAccelerometerInterval(double interval); + + virtual bool isKeypadEnabled(); + virtual void setKeypadEnabled(bool value); + + RT_ADD( + virtual bool isKeyboardEnabled(); + virtual void setKeyboardEnabled(bool value); + + virtual bool isMouseEnabled(); + virtual void setMouseEnabled(bool value); + ) + + void registerScriptKeypadHandler(int nHandler); + void unregisterScriptKeypadHandler(void); + + virtual void keyBackClicked(void); + virtual void keyMenuClicked(void); + + RT_ADD( + void keyDown(enumKeyCodes); + ) + + // 2.2 additions + virtual void setPreviousPriority(int); + virtual int getPreviousPriority(); + + inline CCTouchScriptHandlerEntry* getScriptTouchHandlerEntry() { return m_pScriptTouchHandlerEntry; }; + inline CCScriptHandlerEntry* getScriptKeypadHandlerEntry() { return m_pScriptKeypadHandlerEntry; }; + inline CCScriptHandlerEntry* getScriptAccelerateHandlerEntry() { return m_pScriptAccelerateHandlerEntry; }; + protected: + bool m_bTouchEnabled; + bool m_bAccelerometerEnabled; + bool m_bKeypadEnabled; + RT_ADD( + bool m_bKeyboardEnabled; + bool m_bMouseEnabled; + ) + + private: + // Script touch events handler + CCTouchScriptHandlerEntry* m_pScriptTouchHandlerEntry; + CCScriptHandlerEntry* m_pScriptKeypadHandlerEntry; + CCScriptHandlerEntry* m_pScriptAccelerateHandlerEntry; + + int m_nTouchPriority; + ccTouchesMode m_eTouchMode; + + // 2.2 additions + int m_uPreviousPriority; // no idea + + int excuteScriptTouchHandler(int nEventType, CCTouch *pTouch); + int excuteScriptTouchHandler(int nEventType, CCSet *pTouches); + }; + + + // CCNodeRGBA + class CCRGBAProtocol + { + public: + virtual void setColor(const ccColor3B& color) = 0; + virtual const ccColor3B& getColor(void) = 0; + virtual const ccColor3B& getDisplayedColor(void) = 0; + + virtual GLubyte getDisplayedOpacity(void) = 0; + virtual GLubyte getOpacity(void) = 0; + virtual void setOpacity(GLubyte opacity) = 0; + + virtual void setOpacityModifyRGB(bool bValue) = 0; + + virtual bool isOpacityModifyRGB(void) = 0; + + virtual bool isCascadeColorEnabled(void) = 0; + virtual void setCascadeColorEnabled(bool cascadeColorEnabled) = 0; + + virtual void updateDisplayedColor(const ccColor3B& color) = 0; + + virtual bool isCascadeOpacityEnabled(void) = 0; + virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) = 0; + + virtual void updateDisplayedOpacity(GLubyte opacity) = 0; + }; + + class CCNodeRGBA : public CCNode, public CCRGBAProtocol + { + public: + CCNodeRGBA(); + virtual ~CCNodeRGBA(); + + virtual bool init(); + + static CCNodeRGBA * create(void); + + virtual GLubyte getOpacity(); + virtual GLubyte getDisplayedOpacity(); + virtual void setOpacity(GLubyte opacity); + virtual void updateDisplayedOpacity(GLubyte parentOpacity); + virtual bool isCascadeOpacityEnabled(); + virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); + + virtual const ccColor3B& getColor(void); + virtual const ccColor3B& getDisplayedColor(); + virtual void setColor(const ccColor3B& color); + virtual void updateDisplayedColor(const ccColor3B& parentColor); + virtual bool isCascadeColorEnabled(); + virtual void setCascadeColorEnabled(bool cascadeColorEnabled); + + virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);}; + virtual bool isOpacityModifyRGB() { return false; }; + + protected: + GLubyte _displayedOpacity; + GLubyte _realOpacity; + ccColor3B _displayedColor; + ccColor3B _realColor; + bool _cascadeColorEnabled; + bool _cascadeOpacityEnabled; + }; + + + // CCLayerColor + class CCBlendProtocol + { + public: + virtual void setBlendFunc(ccBlendFunc blendFunc) = 0; + + virtual ccBlendFunc getBlendFunc(void) = 0; + }; + + class CCLayerRGBA : public CCLayer, public CCRGBAProtocol + { + public: + CREATE_FUNC(CCLayerRGBA); + CCLayerRGBA(); + virtual ~CCLayerRGBA(); + + virtual bool init(); + + virtual GLubyte getOpacity(); + virtual GLubyte getDisplayedOpacity(); + virtual void setOpacity(GLubyte opacity); + virtual void updateDisplayedOpacity(GLubyte parentOpacity); + virtual bool isCascadeOpacityEnabled(); + virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); + + virtual const ccColor3B& getColor(); + virtual const ccColor3B& getDisplayedColor(); + virtual void setColor(const ccColor3B& color); + virtual void updateDisplayedColor(const ccColor3B& parentColor); + virtual bool isCascadeColorEnabled(); + virtual void setCascadeColorEnabled(bool cascadeColorEnabled); + + virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);} + virtual bool isOpacityModifyRGB() { return false; } + protected: + GLubyte _displayedOpacity, _realOpacity; + ccColor3B _displayedColor, _realColor; + bool _cascadeOpacityEnabled, _cascadeColorEnabled; + }; + + class CCLayerColor : public CCLayerRGBA, public CCBlendProtocol + { + protected: + ccVertex2F m_pSquareVertices[4]; + ccColor4F m_pSquareColors[4]; + + public: + CCLayerColor(); + virtual ~CCLayerColor(); + + virtual void draw(); + virtual void setContentSize(const CCSize & var); + + static CCLayerColor* create(); + + static CCLayerColor * create(const ccColor4B& color, GLfloat width, GLfloat height); + static CCLayerColor * create(const ccColor4B& color); + + virtual bool init(); + virtual bool initWithColor(const ccColor4B& color, GLfloat width, GLfloat height); + virtual bool initWithColor(const ccColor4B& color); + + void changeWidth(GLfloat w); + void changeHeight(GLfloat h); + void changeWidthAndHeight(GLfloat w ,GLfloat h); + + CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc) + + virtual void setColor(const ccColor3B &color); + virtual void setOpacity(GLubyte opacity); + + void addToVertices(cocos2d::CCPoint, cocos2d::CCPoint, cocos2d::CCPoint); + void setVertices(cocos2d::CCPoint, cocos2d::CCPoint, cocos2d::CCPoint); + + protected: + virtual void updateColor(); + }; + + + // CCLayerGradient + class CCLayerGradient : public CCLayerColor + { + public: + CCLayerGradient() {} + + static CCLayerGradient* create(const ccColor4B& start, const ccColor4B& end); + + static CCLayerGradient* create(const ccColor4B& start, const ccColor4B& end, const CCPoint& v); + + virtual bool init(); + virtual bool initWithColor(const ccColor4B& start, const ccColor4B& end); + + virtual bool initWithColor(const ccColor4B& start, const ccColor4B& end, const CCPoint& v); + + CC_PROPERTY_PASS_BY_REF(ccColor3B, m_startColor, StartColor) + CC_PROPERTY_PASS_BY_REF(ccColor3B, m_endColor, EndColor) + CC_PROPERTY(GLubyte, m_cStartOpacity, StartOpacity) + CC_PROPERTY(GLubyte, m_cEndOpacity, EndOpacity) + CC_PROPERTY_PASS_BY_REF(CCPoint, m_AlongVector, Vector) + + bool getShouldPremultiply() const; + void setShouldPremultiply(bool); + void setValues(cocos2d::_ccColor3B const&, unsigned char, cocos2d::_ccColor3B const&, unsigned char, cocos2d::CCPoint const&); + + protected: + bool m_bCompressedInterpolation; + + public: + virtual void setCompressedInterpolation(bool bCompressedInterpolation); + virtual bool isCompressedInterpolation(); + + static CCLayerGradient* create(); + + protected: + virtual void updateColor(); + }; + + + // CCMenu + enum { + //* priority used by the menu for the event handler + kCCMenuHandlerPriority = -128, + }; + + class CCMenuItem : public CCNodeRGBA + { + public: + bool m_bSelected; + bool m_bEnabled; + + public: + CCMenuItem() + : m_bSelected(false) + , m_bEnabled(false) + , m_pListener(NULL) + , m_pfnSelector(NULL) + , m_nScriptTapHandler(0) + , m_fSizeMult(0.f) + {} + virtual ~CCMenuItem(); + + static CCMenuItem* create(); + static CCMenuItem* create(CCObject *rec, SEL_MenuHandler selector); + bool initWithTarget(CCObject *rec, SEL_MenuHandler selector); + CCRect rect(); + virtual void activate(); + virtual void selected(); + virtual void unselected(); + + virtual void registerScriptTapHandler(int nHandler); + virtual void unregisterScriptTapHandler(void); + int getScriptTapHandler() { return m_nScriptTapHandler; }; + + virtual bool isEnabled(); + virtual void setEnabled(bool value); + virtual bool isSelected(); + + void setTarget(CCObject *rec, SEL_MenuHandler selector); + + public: + CCObject* m_pListener; + SEL_MenuHandler m_pfnSelector; + int m_nScriptTapHandler; + + // 2.2 additions + RT_ADD(float m_fSizeMult = 0.f;) + }; + + class CCMenu : public CCLayerRGBA + { + private: + bool m_bEnabled; + + public: + CCMenu() : m_pSelectedItem(NULL) {} + virtual ~CCMenu(){} + + static CCMenu* create(); + + static CCMenu* create(CCMenuItem* item, ...); + + static CCMenu* createWithArray(CCArray* pArrayOfItems); + + static CCMenu* createWithItem(CCMenuItem* item); + + static CCMenu* createWithItems(CCMenuItem *firstItem, va_list args); + + bool init(); + + bool initWithArray(CCArray* pArrayOfItems); + + void alignItemsVertically(); + void alignItemsVerticallyWithPadding(float padding); + + void alignItemsHorizontally(); + void alignItemsHorizontallyWithPadding(float padding); + + void alignItemsInColumns(unsigned int columns, ...); + void alignItemsInColumns(unsigned int columns, va_list args); + void alignItemsInColumnsWithArray(CCArray* rows); + void alignItemsInRows(unsigned int rows, ...); + void alignItemsInRows(unsigned int rows, va_list args); + void alignItemsInRowsWithArray(CCArray* columns); + + void setHandlerPriority(int newPriority); + + virtual void addChild(CCNode * child); + virtual void addChild(CCNode * child, int zOrder); + virtual void addChild(CCNode * child, int zOrder, int tag); + virtual void registerWithTouchDispatcher(); + virtual void removeChild(CCNode* child, bool cleanup); + + virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); + virtual void ccTouchEnded(CCTouch* touch, CCEvent* event); + virtual void ccTouchCancelled(CCTouch *touch, CCEvent* event); + virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); + + virtual void onExit(); + + virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);} + virtual bool isOpacityModifyRGB(void) { return false;} + + virtual bool isEnabled() { return m_bEnabled; } + virtual void setEnabled(bool value) { m_bEnabled = value; }; + + protected: + CCMenuItem* itemForTouch(CCTouch * touch); + CCMenuItem* itemForTouch(CCTouch * touch, bool); + tCCMenuState m_eState; + CCMenuItem *m_pSelectedItem; + }; + + + // CCMenuItemSprite + class CCMenuItemSprite : public CCMenuItem + { + CC_PROPERTY(CCNode*, m_pNormalImage, NormalImage); + CC_PROPERTY(CCNode*, m_pSelectedImage, SelectedImage); + CC_PROPERTY(CCNode*, m_pDisabledImage, DisabledImage); + public: + CCMenuItemSprite() + :m_pNormalImage(NULL) + ,m_pSelectedImage(NULL) + ,m_pDisabledImage(NULL) + {} + + static CCMenuItemSprite * create(CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite = NULL); + static CCMenuItemSprite * create(CCNode* normalSprite, CCNode* selectedSprite, CCObject* target, SEL_MenuHandler selector); + static CCMenuItemSprite * create(CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite, CCObject* target, SEL_MenuHandler selector); + + bool initWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite, CCObject* target, SEL_MenuHandler selector); + + virtual void selected(); + virtual void unselected(); + virtual void setEnabled(bool bEnabled); + + protected: + virtual void updateImagesVisibility(); + }; + + + // CCMenuItemImage + class CCSpriteFrame : public CCObject + { + public: + // attributes + + inline const CCRect& getRectInPixels(void) { return m_obRectInPixels; } + void setRectInPixels(const CCRect& rectInPixels); + + inline bool isRotated(void) { return m_bRotated; } + inline void setRotated(bool bRotated) { m_bRotated = bRotated; } + + inline const CCRect& getRect(void) { return m_obRect; } + void setRect(const CCRect& rect); + + const CCPoint& getOffsetInPixels(void); + void setOffsetInPixels(const CCPoint& offsetInPixels); + + inline const CCSize& getOriginalSizeInPixels(void) { return m_obOriginalSizeInPixels; } + inline void setOriginalSizeInPixels(const CCSize& sizeInPixels) { m_obOriginalSizeInPixels = sizeInPixels; } + + inline const CCSize& getOriginalSize(void) { return m_obOriginalSize; } + inline void setOriginalSize(const CCSize& sizeInPixels) { m_obOriginalSize = sizeInPixels; } + + CCTexture2D* getTexture(void); + void setTexture(CCTexture2D* pobTexture); + + const CCPoint& getOffset(void); + void setOffset(const CCPoint& offsets); + + public: + ~CCSpriteFrame(void); + virtual CCObject* copyWithZone(CCZone *pZone); + + static CCSpriteFrame* create(const char* filename, const CCRect& rect); + + static CCSpriteFrame* create(const char* filename, const CCRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSize); + + static CCSpriteFrame* createWithTexture(CCTexture2D* pobTexture, const CCRect& rect); + + static CCSpriteFrame* createWithTexture(CCTexture2D* pobTexture, const CCRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSize); + + public: + bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect); + + bool initWithTextureFilename(const char* filename, const CCRect& rect); + + bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSize); + + bool initWithTextureFilename(const char* filename, const CCRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSize); + + std::string getFrameName() const; + void setFrameName(std::string); + + protected: + CCPoint m_obOffset; + CCSize m_obOriginalSize; + CCRect m_obRectInPixels; + bool m_bRotated; + CCRect m_obRect; + CCPoint m_obOffsetInPixels; + CCSize m_obOriginalSizeInPixels; + CCTexture2D *m_pobTexture; + std::string m_strTextureFilename; + RT_ADD( std::string m_strFrameName; ) + }; + + class CCMenuItemImage : public CCMenuItemSprite + { + public: + CCMenuItemImage(){} + virtual ~CCMenuItemImage(){} + + static CCMenuItemImage* create(const char *normalImage, const char *selectedImage); + static CCMenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage); + static CCMenuItemImage* create(const char *normalImage, const char *selectedImage, CCObject* target, SEL_MenuHandler selector); + static CCMenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler selector); + + bool init(); + bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler selector); + void setNormalSpriteFrame(CCSpriteFrame* frame); + void setSelectedSpriteFrame(CCSpriteFrame* frame); + void setDisabledSpriteFrame(CCSpriteFrame* frame); + + static CCMenuItemImage* create(); + }; + + + // CCScene + class CCScene; + class CCSceneDelegate { + public: + virtual void willSwitchToScene(CCScene* scene) {} + }; + + class CCScene : public CCNode + { + public: + CCScene(); + virtual ~CCScene(); + bool init(); + + static CCScene* create(void); + + CCScene(const CCScene&); + CCScene& operator=(const CCScene&); + + int getHighestChildZ(void); + + CCSceneDelegate* m_pDelegate; + }; + + + // CCSceneTransitionDelegate + RT_ADD( + class CCSceneTransitionDelegate { + public: + virtual void sceneWillResume(void) {} + }; + ) + + // CCSprite + class CCTextureProtocol : public CCBlendProtocol + { + public: + virtual CCTexture2D* getTexture(void) = 0; + virtual void setTexture(CCTexture2D *texture) = 0; + }; + + class CCTextureAtlas : public CCObject + { + protected: + GLushort* m_pIndices; + #if CC_TEXTURE_ATLAS_USE_VAO + GLuint m_uVAOname; + #endif + GLuint m_pBuffersVBO[2]; //0: vertex 1: indices + bool m_bDirty; //indicates whether or not the array buffer of the VBO needs to be updated + + + /** quantity of quads that are going to be drawn */ + CC_PROPERTY_READONLY(unsigned int, m_uTotalQuads, TotalQuads) + /** quantity of quads that can be stored with the current texture atlas size */ + CC_PROPERTY_READONLY(unsigned int, m_uCapacity, Capacity) + /** Texture of the texture atlas */ + CC_PROPERTY(CCTexture2D *, m_pTexture, Texture) + /** Quads that are going to be rendered */ + CC_PROPERTY(ccV3F_C4B_T2F_Quad *, m_pQuads, Quads) + + public: + CCTextureAtlas(); + virtual ~CCTextureAtlas(); + const char* description(); + + static CCTextureAtlas* create(const char* file , unsigned int capacity); + + bool initWithFile(const char* file, unsigned int capacity); + + static CCTextureAtlas* createWithTexture(CCTexture2D *texture, unsigned int capacity); + + + bool initWithTexture(CCTexture2D *texture, unsigned int capacity); + + void updateQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index); + void insertQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index); + void insertQuads(ccV3F_C4B_T2F_Quad* quads, unsigned int index, unsigned int amount); + void insertQuadFromIndex(unsigned int fromIndex, unsigned int newIndex); + void removeQuadAtIndex(unsigned int index); + void removeQuadsAtIndex(unsigned int index, unsigned int amount); + void removeAllQuads(); + + + bool resizeCapacity(unsigned int n); + + void increaseTotalQuadsWith(unsigned int amount); + + void moveQuadsFromIndex(unsigned int oldIndex, unsigned int amount, unsigned int newIndex); + + void moveQuadsFromIndex(unsigned int index, unsigned int newIndex); + + void fillWithEmptyQuadsFromIndex(unsigned int index, unsigned int amount); + + void drawNumberOfQuads(unsigned int n); + + void drawNumberOfQuads(unsigned int n, unsigned int start); + + void drawQuads(); + void listenBackToForeground(CCObject *obj); + + inline bool isDirty(void) { return m_bDirty; } + inline void setDirty(bool bDirty) { m_bDirty = bDirty; } + + private: + void setupIndices(); + void mapBuffers(); + #if CC_TEXTURE_ATLAS_USE_VAO + void setupVBOandVAO(); + #else + void setupVBO(); + #endif + }; + + #define kDefaultSpriteBatchCapacity 29 + class CCSprite; + class CCSpriteBatchNode : public CCNode, public CCTextureProtocol + { + public: + CCSpriteBatchNode(); + ~CCSpriteBatchNode(); + + inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas; } + inline void setTextureAtlas(CCTextureAtlas* textureAtlas) + { + if (textureAtlas != m_pobTextureAtlas) + { + CC_SAFE_RETAIN(textureAtlas); + CC_SAFE_RELEASE(m_pobTextureAtlas); + m_pobTextureAtlas = textureAtlas; + } + } + + inline CCArray* getDescendants(void) { return m_pobDescendants; } + + static CCSpriteBatchNode* createWithTexture(CCTexture2D* tex, unsigned int capacity); + static CCSpriteBatchNode* createWithTexture(CCTexture2D* tex) { + return CCSpriteBatchNode::createWithTexture(tex, kDefaultSpriteBatchCapacity); + } + + static CCSpriteBatchNode* create(const char* fileImage, unsigned int capacity); + static CCSpriteBatchNode* create(const char* fileImage) { + return CCSpriteBatchNode::create(fileImage, kDefaultSpriteBatchCapacity); + } + + bool initWithTexture(CCTexture2D *tex, unsigned int capacity); + bool initWithFile(const char* fileImage, unsigned int capacity); + bool init(); + + void removeChildAtIndex(unsigned int index, bool doCleanup); + + void insertChild(CCSprite *child, unsigned int index); + void appendChild(CCSprite* sprite); + void removeSpriteFromAtlas(CCSprite *sprite); + + unsigned int rebuildIndexInOrder(CCSprite *parent, unsigned int index); + unsigned int highestAtlasIndexInChild(CCSprite *sprite); + unsigned int lowestAtlasIndexInChild(CCSprite *sprite); + unsigned int atlasIndexForChild(CCSprite *sprite, int z); + void reorderBatch(bool reorder); + // CCTextureProtocol + virtual CCTexture2D* getTexture(void); + virtual void setTexture(CCTexture2D *texture); + virtual void setBlendFunc(ccBlendFunc blendFunc); + virtual ccBlendFunc getBlendFunc(void); + + virtual void visit(void); + virtual void addChild(CCNode * child); + virtual void addChild(CCNode * child, int zOrder); + virtual void addChild(CCNode * child, int zOrder, int tag); + virtual void reorderChild(CCNode * child, int zOrder); + + virtual void removeChild(CCNode* child, bool cleanup); + virtual void removeAllChildrenWithCleanup(bool cleanup); + virtual void sortAllChildren(); + virtual void draw(void); + + protected: + void insertQuadFromSprite(CCSprite *sprite, unsigned int index); + void updateQuadFromSprite(CCSprite *sprite, unsigned int index); + CCSpriteBatchNode * addSpriteWithoutQuad(CCSprite*child, unsigned int z, int aTag); + + RT_ADD( + bool getManualSortChildren(void)const; + int getAtlasCapacity(void); + public: + int getUsedAtlasCapacity(void); + void increaseAtlasCapacity(unsigned int); + void increaseAtlasCapacity(); + protected: + void manualSortAllChildren(void); + void setManualSortChildren(bool); + ); + + private: + void updateAtlasIndex(CCSprite* sprite, int* curIndex); + void swap(int oldIndex, int newIndex); + void updateBlendFunc(); + + protected: + CCTextureAtlas *m_pobTextureAtlas; + ccBlendFunc m_blendFunc; + + // all descendants: children, gran children, etc... + CCArray* m_pobDescendants; + + RT_ADD( + bool m_bManualSortChildren; + bool m_bManualSortAllChildrenDirty; + ) + }; + + class CCSprite : public CCNodeRGBA, public CCTextureProtocol + { + public: + static CCSprite* create(); + static CCSprite* create(const char *pszFileName); + static CCSprite* create(const char *pszFileName, const CCRect& rect); + static CCSprite* createWithTexture(CCTexture2D *pTexture); + static CCSprite* createWithTexture(CCTexture2D *pTexture, const CCRect& rect); + static CCSprite* createWithSpriteFrame(CCSpriteFrame *pSpriteFrame); + static CCSprite* createWithSpriteFrameName(const char *pszSpriteFrameName); + + CCSprite(void); + + virtual ~CCSprite(void); + virtual bool init(void); + virtual bool initWithTexture(CCTexture2D *pTexture); + virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect); + virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect, bool rotated); + virtual bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame); + virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName); + virtual bool initWithFile(const char *pszFilename); + virtual bool initWithFile(const char *pszFilename, const CCRect& rect); + + virtual void setTexture(CCTexture2D *texture); + virtual CCTexture2D* getTexture(void); + inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = blendFunc; } + inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; } + + RT_ADD( + virtual void setChildColor(const ccColor3B&); + virtual void setChildOpacity(GLubyte); + ) + + virtual void setScaleX(float fScaleX); + virtual void setScaleY(float fScaleY); + virtual void setPosition(const CCPoint& pos); + virtual void setRotation(float fRotation); + virtual void setRotationX(float fRotationX); + virtual void setRotationY(float fRotationY); + virtual void setSkewX(float sx); + virtual void setSkewY(float sy); + virtual void removeChild(CCNode* pChild, bool bCleanup); + virtual void removeAllChildrenWithCleanup(bool bCleanup); + virtual void reorderChild(CCNode *pChild, int zOrder); + virtual void addChild(CCNode *pChild); + virtual void addChild(CCNode *pChild, int zOrder); + virtual void addChild(CCNode *pChild, int zOrder, int tag); + virtual void sortAllChildren(); + virtual void setScale(float fScale); + virtual void setVertexZ(float fVertexZ); + virtual void setAnchorPoint(const CCPoint& anchor); + virtual void ignoreAnchorPointForPosition(bool value); + virtual void setVisible(bool bVisible); + virtual void draw(void); + + virtual void setColor(const ccColor3B& color3); + virtual void updateDisplayedColor(const ccColor3B& parentColor); + virtual void setOpacity(GLubyte opacity); + virtual void setOpacityModifyRGB(bool modify); + virtual bool isOpacityModifyRGB(void); + virtual void updateDisplayedOpacity(GLubyte parentOpacity); + + virtual void updateTransform(void); + + virtual CCSpriteBatchNode* getBatchNode(void); + virtual void setBatchNode(CCSpriteBatchNode *pobSpriteBatchNode); + + RT_ADD( + virtual void refreshTextureRect(void); + ) + + virtual void setTextureRect(const CCRect& rect); + virtual void setTextureRect(const CCRect& rect, bool rotated, const CCSize& untrimmedSize); + virtual void setVertexRect(const CCRect& rect); + + virtual void setDisplayFrame(CCSpriteFrame *pNewFrame); + + virtual bool isFrameDisplayed(CCSpriteFrame *pFrame); + + virtual CCSpriteFrame* displayFrame(void); + + inline virtual bool isDirty(void) { return m_bDirty; } + + inline virtual void setDirty(bool bDirty) { m_bDirty = bDirty; } + + inline ccV3F_C4B_T2F_Quad getQuad(void) { return m_sQuad; } + + inline bool isTextureRectRotated(void) { return m_bRectRotated; } + + inline unsigned int getAtlasIndex(void) { return m_uAtlasIndex; } + + inline void setAtlasIndex(unsigned int uAtlasIndex) { m_uAtlasIndex = uAtlasIndex; } + + inline const CCRect& getTextureRect(void) { return m_obRect; } + + inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas; } + + inline void setTextureAtlas(CCTextureAtlas *pobTextureAtlas) { m_pobTextureAtlas = pobTextureAtlas; } + + inline const CCPoint& getOffsetPosition(void) { return m_obOffsetPosition; } + + + bool isFlipX(void); + void setFlipX(bool bFlipX); + + bool isFlipY(void); + void setFlipY(bool bFlipY); + + cocos2d::CCPoint const& getUnflippedOffsetPosition(); + bool getUseVertexMod() const; + void setUseVertexMod(bool); + + protected: + void updateColor(void); + RT_REMOVE( virtual void setTextureCoords(CCRect rect); ) + RT_ADD( virtual void setTextureCoords(const CCRect& rect); ) + virtual void updateBlendFunc(void); + virtual void setReorderChildDirtyRecursively(void); + virtual void setDirtyRecursively(bool bValue); + + CCTextureAtlas* m_pobTextureAtlas; /// CCSpriteBatchNode texture atlas (weak reference) + unsigned int m_uAtlasIndex; /// Absolute (real) Index on the SpriteSheet + CCSpriteBatchNode* m_pobBatchNode; /// Used batch node (weak reference) + + bool m_bDirty; /// Whether the sprite needs to be updated + bool m_bRecursiveDirty; /// Whether all of the sprite's children needs to be updated + bool m_bHasChildren; /// Whether the sprite contains children + bool m_bShouldBeHidden; /// should not be drawn because one of the ancestors is not visible + CCAffineTransform m_transformToBatch; + + ccBlendFunc m_sBlendFunc; /// It's required for CCTextureProtocol inheritance + CCTexture2D* m_pobTexture; /// CCTexture2D object that is used to render the sprite + + CCRect m_obRect; /// Retangle of CCTexture2D + bool m_bRectRotated; /// Whether the texture is rotated + + CCPoint m_obOffsetPosition; + CCPoint m_obUnflippedOffsetPositionFromCenter; + + ccV3F_C4B_T2F_Quad m_sQuad; + + bool m_bOpacityModifyRGB; + + bool m_bFlipX; /// Whether the sprite is flipped horizaontally or not. + bool m_bFlipY; /// Whether the sprite is flipped vertically or not. + + RT_ADD( + CC_SYNTHESIZE_NV(bool, m_bDontDraw, DontDraw); + CC_SYNTHESIZE_NV(float, m_fTlVertexMod, TlVertexMod); + CC_SYNTHESIZE_NV(float, m_fTrVertexMod, TrVertexMod); + CC_SYNTHESIZE_NV(float, m_fBlVertexMod, BlVertexMod); + CC_SYNTHESIZE_NV(float, m_fBrVertexMod, BrVertexMod); + PAD(16); + bool m_bUnknown; + // 2.2 additions + // int m_nUnknown; + ) + }; + + + // CCAnimation + class CCAnimation : public CCObject + { + public: + CCAnimation(); + ~CCAnimation(void); + public: + static CCAnimation* create(void); + + static CCAnimation* createWithSpriteFrames(CCArray* arrayOfSpriteFrameNames, float delay = 0.0f); + + static CCAnimation* create(CCArray *arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops); + static CCAnimation* create(CCArray *arrayOfAnimationFrameNames, float delayPerUnit) { + return CCAnimation::create(arrayOfAnimationFrameNames, delayPerUnit, 1); + } + + void addSpriteFrame(CCSpriteFrame *pFrame); + void addSpriteFrameWithFileName(const char *pszFileName); + void addSpriteFrameWithTexture(CCTexture2D* pobTexture, const CCRect& rect); + + bool init(); + bool initWithSpriteFrames(CCArray *pFrames, float delay = 0.0f); + bool initWithAnimationFrames(CCArray* arrayOfAnimationFrames, float delayPerUnit, unsigned int loops); + + virtual CCObject* copyWithZone(CCZone* pZone); + + CC_SYNTHESIZE_READONLY(float, m_fTotalDelayUnits, TotalDelayUnits) + + CC_SYNTHESIZE(float, m_fDelayPerUnit, DelayPerUnit) + + CC_PROPERTY_READONLY(float, m_fDuration, Duration) + + CC_SYNTHESIZE_RETAIN(CCArray*, m_pFrames, Frames) + + CC_SYNTHESIZE(bool, m_bRestoreOriginalFrame, RestoreOriginalFrame) + + CC_SYNTHESIZE(unsigned int, m_uLoops, Loops) + }; + + // CCActionInterval + class CCFiniteTimeAction : public CCAction + { + public: + CCFiniteTimeAction() + : m_fDuration(0) + {} + virtual ~CCFiniteTimeAction(){} + inline float getDuration(void) { return m_fDuration; } + inline void setDuration(float duration) { m_fDuration = duration; } + + virtual CCFiniteTimeAction* reverse(void); + protected: + //! duration in seconds + float m_fDuration; + }; + + class CCActionInterval : public CCFiniteTimeAction + { + public: + CCActionInterval() {} + + inline float getElapsed(void) { return m_elapsed; } + + bool initWithDuration(float d); + + virtual bool isDone(void); + virtual CCObject* copyWithZone(CCZone* pZone); + virtual void step(float dt); + virtual void startWithTarget(CCNode *pTarget); + virtual CCActionInterval* reverse(void); + + public: + + static CCActionInterval* create(float d); + + public: + void setAmplitudeRate(float amp); + float getAmplitudeRate(void); + + // 2.2 addition + bool getM_bFirstTick(); // rob were you like high on something when you wrote this + + protected: + float m_elapsed; + bool m_bFirstTick; + }; + + + // CCAnimate + class CCAnimate : public CCActionInterval + { + public: + CCAnimate(); + ~CCAnimate(); + + /** initializes the action with an Animation and will restore the original frame when the animation is over */ + bool initWithAnimation(CCAnimation *pAnimation); + + /** + * @js NA + * @lua NA + */ + virtual CCObject* copyWithZone(CCZone* pZone); + virtual void startWithTarget(CCNode *pTarget); + virtual void stop(void); + virtual void update(float t); + virtual CCActionInterval* reverse(void); + + // 2.2 addition + bool getRecenterChildren() const; + bool getRecenterFrames() const; + void setRecenterChildren(bool recenter); + void setRecenterFrames(bool recenter); + + public: + /** creates the action with an Animation and will restore the original frame when the animation is over */ + static CCAnimate* create(CCAnimation *pAnimation); + CC_SYNTHESIZE_RETAIN(CCAnimation*, m_pAnimation, Animation) + protected: + std::vector* m_pSplitTimes; + int m_nNextFrame; + CCSpriteFrame* m_pOrigFrame; + unsigned int m_uExecutedLoops; + }; + + + // CCScaleTo + class CCScaleTo : public CCActionInterval + { + public: + bool initWithDuration(float duration, float s); + + bool initWithDuration(float duration, float sx, float sy); + virtual CCObject* copyWithZone(CCZone* pZone); + virtual void startWithTarget(CCNode *pTarget); + virtual void update(float time); + + public: + static CCScaleTo* create(float duration, float s); + + static CCScaleTo* create(float duration, float sx, float sy); + protected: + float m_fScaleX; + float m_fScaleY; + float m_fStartScaleX; + float m_fStartScaleY; + float m_fEndScaleX; + float m_fEndScaleY; + float m_fDeltaX; + float m_fDeltaY; + }; + + + // CCRenderTexture + class CCRenderTexture : public CCNode + { + CC_PROPERTY(CCSprite*, m_pSprite, Sprite) + public: + CCRenderTexture(); + virtual ~CCRenderTexture(); + + virtual void visit(); + virtual void draw(); + + static CCRenderTexture * create(int w ,int h, CCTexture2DPixelFormat eFormat, GLuint uDepthStencilFormat); + + static CCRenderTexture * create(int w, int h, CCTexture2DPixelFormat eFormat); + + static CCRenderTexture * create(int w, int h); + + bool initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eFormat); + + bool initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eFormat, GLuint uDepthStencilFormat); + + void begin(); + + void beginWithClear(float r, float g, float b, float a); + + void beginWithClear(float r, float g, float b, float a, float depthValue); + + void beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue); + + inline void endToLua(){ end();}; + + void end(); + + void clear(float r, float g, float b, float a); + + void clearDepth(float depthValue); + + void clearStencil(int stencilValue); + CCImage* newCCImage(bool flipImage = true); + + bool saveToFile(const char *szFilePath); + + bool saveToFile(const char *name, tCCImageFormat format); + + void listenToBackground(CCObject *obj); + + void listenToForeground(CCObject *obj); + + unsigned int getClearFlags() const; + void setClearFlags(unsigned int uClearFlags); + + const ccColor4F& getClearColor() const; + void setClearColor(const ccColor4F &clearColor); + + float getClearDepth() const; + void setClearDepth(float fClearDepth); + + int getClearStencil() const; + void setClearStencil(float fClearStencil); + + bool isAutoDraw() const; + void setAutoDraw(bool bAutoDraw); + + void updateInternalScale(float, float); + + private: + void beginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue, GLbitfield flags); + + protected: + GLuint m_uFBO; + GLuint m_uDepthRenderBufffer; + GLint m_nOldFBO; + CCTexture2D* m_pTexture; + CCTexture2D* m_pTextureCopy; // a copy of m_pTexture + CCImage* m_pUITextureImage; + GLenum m_ePixelFormat; + + // code for "auto" update + GLbitfield m_uClearFlags; + ccColor4F m_sClearColor; + GLclampf m_fClearDepth; + GLint m_nClearStencil; + bool m_bAutoDraw; + }; + + + // CCDrawNode + class CCDrawNode : public CCNodeRGBA + { + protected: + + GLuint m_uVao; + GLuint m_uVbo; + + unsigned int m_uBufferCapacity; + GLsizei m_nBufferCount; + ccV2F_C4B_T2F *m_pBuffer; + + ccBlendFunc m_sBlendFunc; + + bool m_bDirty; + + public: + static CCDrawNode* create(); + virtual ~CCDrawNode(); + + virtual bool init(); + virtual void draw(); + + #if COMP_GD_VERSION > 22000 + /** draw a dot at a position, with a given radius and color */ + bool drawDot(const CCPoint &pos, float radius, const ccColor4F &color); + + /** draw a segment with a radius and color */ + bool drawSegment(const CCPoint &from, const CCPoint &to, float radius, const ccColor4F &color); + + /** draw a polygon with a fill color and line color + * @code + * when this funciton bound to js,the input params are changed + * js:var drawPolygon(var verts, var fillColor,var borderWidth,var borderColor) + * @endcode + */ + bool drawPolygon(CCPoint *verts, unsigned int count, const ccColor4F &fillColor, float borderWidth, const ccColor4F &borderColor); + + bool drawCircle(cocos2d::CCPoint const&, float, cocos2d::_ccColor4F const&, float, cocos2d::_ccColor4F const&, unsigned int); + void drawCubicBezier(cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, unsigned int, cocos2d::_ccColor4F const&); + void drawPreciseCubicBezier(cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, unsigned int, cocos2d::_ccColor4F const&); + bool drawLines(cocos2d::CCPoint*, unsigned int, float, cocos2d::_ccColor4F const&); + bool drawRect(cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::_ccColor4F const&, float, cocos2d::_ccColor4F const&); + #else + /** draw a dot at a position, with a given radius and color */ + void drawDot(const CCPoint &pos, float radius, const ccColor4F &color); + + /** draw a segment with a radius and color */ + void drawSegment(const CCPoint &from, const CCPoint &to, float radius, const ccColor4F &color); + + /** draw a polygon with a fill color and line color + * @code + * when this funciton bound to js,the input params are changed + * js:var drawPolygon(var verts, var fillColor,var borderWidth,var borderColor) + * @endcode + */ + void drawPolygon(CCPoint *verts, unsigned int count, const ccColor4F &fillColor, float borderWidth, const ccColor4F &borderColor); + + void drawCircle(cocos2d::CCPoint const&, float, cocos2d::_ccColor4F const&, float, cocos2d::_ccColor4F const&, unsigned int); + void drawCubicBezier(cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, unsigned int, cocos2d::_ccColor4F const&); + void drawPreciseCubicBezier(cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::CCPoint const&, unsigned int, cocos2d::_ccColor4F const&); + void drawLines(cocos2d::CCPoint*, unsigned int, float, cocos2d::_ccColor4F const&); + void drawRect(cocos2d::CCPoint const&, cocos2d::CCPoint const&, cocos2d::_ccColor4F const&, float, cocos2d::_ccColor4F const&); + #endif + + void clear(); + ccBlendFunc getBlendFunc() const; + void setBlendFunc(const ccBlendFunc &blendFunc); + + CCDrawNode(); + + void listenBackToForeground(CCObject *obj); + private: + void ensureCapacity(unsigned int count); + void render(); + }; + + + // CCParticleSystemQuad + class CCParticleSystem; + #define kCCParticleDefaultCapacity 500 + class CCParticleBatchNode : public CCNode, public CCTextureProtocol + { + public: + CCParticleBatchNode(); + virtual ~CCParticleBatchNode(); + + static CCParticleBatchNode* createWithTexture(CCTexture2D *tex, unsigned int capacity = kCCParticleDefaultCapacity); + + static CCParticleBatchNode* create(const char* fileImage, unsigned int capacity = kCCParticleDefaultCapacity); + + bool initWithTexture(CCTexture2D *tex, unsigned int capacity); + + bool initWithFile(const char* fileImage, unsigned int capacity); + + virtual void addChild(CCNode * child); + virtual void addChild(CCNode * child, int zOrder); + virtual void addChild(CCNode * child, int zOrder, int tag); + + void insertChild(CCParticleSystem* pSystem, unsigned int index); + + virtual void removeChild(CCNode* child, bool cleanup); + virtual void reorderChild(CCNode * child, int zOrder); + void removeChildAtIndex(unsigned int index, bool doCleanup); + void removeAllChildrenWithCleanup(bool doCleanup); + void disableParticle(unsigned int particleIndex); + virtual void draw(void); + virtual CCTexture2D* getTexture(void); + virtual void setTexture(CCTexture2D *texture); + virtual void setBlendFunc(ccBlendFunc blendFunc); + virtual ccBlendFunc getBlendFunc(void); + + void visit(); + + private: + void updateAllAtlasIndexes(); + void increaseAtlasCapacityTo(unsigned int quantity); + unsigned int searchNewPositionInChildrenForZ(int z); + void getCurrentIndex(unsigned int* oldIndex, unsigned int* newIndex, CCNode* child, int z); + unsigned int addChildHelper(CCParticleSystem* child, int z, int aTag); + void updateBlendFunc(void); + CC_SYNTHESIZE(CCTextureAtlas*, m_pTextureAtlas, TextureAtlas); + private: + ccBlendFunc m_tBlendFunc; + }; + + class CCParticleSystem : public CCNode, public CCTextureProtocol + { + protected: + std::string m_sPlistFile; + //! time elapsed since the start of the system (in seconds) + float m_fElapsed; + + // Different modes + //! Mode A:Gravity + Tangential Accel + Radial Accel + struct { + /** Gravity value. Only available in 'Gravity' mode. */ + CCPoint gravity; + /** speed of each particle. Only available in 'Gravity' mode. */ + float speed; + /** speed variance of each particle. Only available in 'Gravity' mode. */ + float speedVar; + /** tangential acceleration of each particle. Only available in 'Gravity' mode. */ + float tangentialAccel; + /** tangential acceleration variance of each particle. Only available in 'Gravity' mode. */ + float tangentialAccelVar; + /** radial acceleration of each particle. Only available in 'Gravity' mode. */ + float radialAccel; + /** radial acceleration variance of each particle. Only available in 'Gravity' mode. */ + float radialAccelVar; + /** set the rotation of each particle to its direction Only available in 'Gravity' mode. */ + bool rotationIsDir; + } modeA; + + //! Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode) + struct { + /** The starting radius of the particles. Only available in 'Radius' mode. */ + float startRadius; + /** The starting radius variance of the particles. Only available in 'Radius' mode. */ + float startRadiusVar; + /** The ending radius of the particles. Only available in 'Radius' mode. */ + float endRadius; + /** The ending radius variance of the particles. Only available in 'Radius' mode. */ + float endRadiusVar; + /** Number of degrees to rotate a particle around the source pos per second. Only available in 'Radius' mode. */ + float rotatePerSecond; + /** Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. */ + float rotatePerSecondVar; + } modeB; + + //! Array of particles + tCCParticle *m_pParticles; + + // color modulate + // BOOL colorModulate; + + //! How many particles can be emitted per second + float m_fEmitCounter; + + //! particle idx + unsigned int m_uParticleIdx; + + // Optimization + //CC_UPDATE_PARTICLE_IMP updateParticleImp; + //SEL updateParticleSel; + + /** weak reference to the CCSpriteBatchNode that renders the CCSprite */ + CC_PROPERTY(CCParticleBatchNode*, m_pBatchNode, BatchNode); + + RT_REMOVE( + CC_SYNTHESIZE(unsigned int, m_uAtlasIndex, AtlasIndex); + ) + RT_ADD( + CC_SYNTHESIZE_NV(unsigned int, m_uAtlasIndex, AtlasIndex); + ) + + //true if scaled or rotated + bool m_bTransformSystemDirty; + // Number of allocated particles + unsigned int m_uAllocatedParticles; + + /** Is the emitter active */ + bool m_bIsActive; + /** Quantity of particles that are being simulated at the moment */ + CC_PROPERTY_READONLY(unsigned int, m_uParticleCount, ParticleCount) + /** How many seconds the emitter will run. -1 means 'forever' */ + CC_PROPERTY(float, m_fDuration, Duration) + /** sourcePosition of the emitter */ + CC_PROPERTY_PASS_BY_REF(CCPoint, m_tSourcePosition, SourcePosition) + /** Position variance of the emitter */ + CC_PROPERTY_PASS_BY_REF(CCPoint, m_tPosVar, PosVar) + /** life, and life variation of each particle */ + CC_PROPERTY(float, m_fLife, Life) + /** life variance of each particle */ + CC_PROPERTY(float, m_fLifeVar, LifeVar) + /** angle and angle variation of each particle */ + CC_PROPERTY(float, m_fAngle, Angle) + /** angle variance of each particle */ + CC_PROPERTY(float, m_fAngleVar, AngleVar) + + ////////////////////////////////////////////////////////////////////////// + public: + // mode A + virtual const CCPoint& getGravity(); + virtual void setGravity(const CCPoint& g); + virtual float getSpeed(); + virtual void setSpeed(float speed); + virtual float getSpeedVar(); + virtual void setSpeedVar(float speed); + virtual float getTangentialAccel(); + virtual void setTangentialAccel(float t); + virtual float getTangentialAccelVar(); + virtual void setTangentialAccelVar(float t); + virtual float getRadialAccel(); + virtual void setRadialAccel(float t); + virtual float getRadialAccelVar(); + virtual void setRadialAccelVar(float t); + virtual bool getRotationIsDir(); + virtual void setRotationIsDir(bool t); + // mode B + virtual float getStartRadius(); + virtual void setStartRadius(float startRadius); + virtual float getStartRadiusVar(); + virtual void setStartRadiusVar(float startRadiusVar); + virtual float getEndRadius(); + virtual void setEndRadius(float endRadius); + virtual float getEndRadiusVar(); + virtual void setEndRadiusVar(float endRadiusVar); + virtual float getRotatePerSecond(); + virtual void setRotatePerSecond(float degrees); + virtual float getRotatePerSecondVar(); + virtual void setRotatePerSecondVar(float degrees); + + RT_ADD ( + virtual void setVisible(bool visible); + ) + + virtual void setScale(float s); + virtual void setRotation(float newRotation); + virtual void setScaleX(float newScaleX); + virtual void setScaleY(float newScaleY); + + virtual bool isActive(); + virtual bool isBlendAdditive(); + virtual void setBlendAdditive(bool value); + ////////////////////////////////////////////////////////////////////////// + + /** start size in pixels of each particle */ + CC_PROPERTY(float, m_fStartSize, StartSize) + /** size variance in pixels of each particle */ + CC_PROPERTY(float, m_fStartSizeVar, StartSizeVar) + /** end size in pixels of each particle */ + CC_PROPERTY(float, m_fEndSize, EndSize) + /** end size variance in pixels of each particle */ + CC_PROPERTY(float, m_fEndSizeVar, EndSizeVar) + /** start color of each particle */ + CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tStartColor, StartColor) + /** start color variance of each particle */ + CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tStartColorVar, StartColorVar) + /** end color and end color variation of each particle */ + CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tEndColor, EndColor) + /** end color variance of each particle */ + CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tEndColorVar, EndColorVar) + //* initial angle of each particle + CC_PROPERTY(float, m_fStartSpin, StartSpin) + //* initial angle of each particle + CC_PROPERTY(float, m_fStartSpinVar, StartSpinVar) + //* initial angle of each particle + CC_PROPERTY(float, m_fEndSpin, EndSpin) + //* initial angle of each particle + CC_PROPERTY(float, m_fEndSpinVar, EndSpinVar) + /** emission rate of the particles */ + CC_PROPERTY(float, m_fEmissionRate, EmissionRate) + /** maximum particles of the system */ + CC_PROPERTY(unsigned int, m_uTotalParticles, TotalParticles) + /** conforms to CocosNodeTexture protocol */ + CC_PROPERTY(CCTexture2D*, m_pTexture, Texture) + /** conforms to CocosNodeTexture protocol */ + CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc) + /** does the alpha value modify color */ + CC_PROPERTY(bool, m_bOpacityModifyRGB, OpacityModifyRGB) + + /** whether or not the particles are using blend additive. + If enabled, the following blending function will be used. + @code + source blend function = GL_SRC_ALPHA; + dest blend function = GL_ONE; + @endcode + */ + bool m_bIsBlendAdditive; + /** particles movement type: Free or Grouped + @since v0.8 + */ + CC_PROPERTY(tCCPositionType, m_ePositionType, PositionType) + /** whether or not the node will be auto-removed when it has no particles left. + By default it is false. + @since v0.8 + */ + protected: + bool m_bIsAutoRemoveOnFinish; + public: + virtual bool isAutoRemoveOnFinish(); + virtual void setAutoRemoveOnFinish(bool var); + + /** Switch between different kind of emitter modes: + - kCCParticleModeGravity: uses gravity, speed, radial and tangential acceleration + - kCCParticleModeRadius: uses radius movement + rotation + */ + CC_PROPERTY(int, m_nEmitterMode, EmitterMode) + + public: + /** + * @js ctor + */ + CCParticleSystem(); + /** + * @js NA + * @lua NA + */ + virtual ~CCParticleSystem(); + + /** creates an initializes a CCParticleSystem from a plist file. + This plist files can be created manually or with Particle Designer: + http://particledesigner.71squared.com/ + @since v2.0 + */ + static CCParticleSystem * create(const char *plistFile); + + //! create a system with a fixed number of particles + static CCParticleSystem* createWithTotalParticles(unsigned int numberOfParticles); + + /** initializes a CCParticleSystem*/ + bool init(); + /** initializes a CCParticleSystem from a plist file. + This plist files can be created manually or with Particle Designer: + http://particledesigner.71squared.com/ + @since v0.99.3 + */ + bool initWithFile(const char *plistFile, bool); + + /** initializes a CCQuadParticleSystem from a CCDictionary. + @since v0.99.3 + */ + bool initWithDictionary(CCDictionary *dictionary, bool); + + /** initializes a particle system from a NSDictionary and the path from where to load the png + @since v2.1 + */ + bool initWithDictionary(CCDictionary *dictionary, const char *dirname, bool); + + //! Initializes a system with a fixed number of particles + virtual bool initWithTotalParticles(unsigned int numberOfParticles, bool); + //! Add a particle to the emitter + bool addParticle(); + //! Initializes a particle + void initParticle(tCCParticle* particle); + //! stop emitting particles. Running particles will continue to run until they die + void stopSystem(); + //! Kill all living particles. + void resetSystem(); + RT_ADD( + void resumeSystem(); + ) + //! whether or not the system is full + bool isFull(); + + //! should be overridden by subclasses + virtual void updateQuadWithParticle(tCCParticle* particle, const CCPoint& newPosition); + //! should be overridden by subclasses + virtual void postStep(); + + virtual void update(float dt); + virtual void updateWithNoTime(void); + + protected: + virtual void updateBlendFunc(); + + RT_ADD( + // saved/loaded in loadDefaults, loadScaledDefaults and saveDefaults + + float m_fDefaultStartSize; + float m_fDefaultStartSizeVar; + // saved as m_fEndSize but not loaded, + // probably was supposed to be m_fDefaultEndSizeVar and saved and loaded as m_fEndSizeVar but was scrapped? + float m_fDefaultEndSize2; + float m_fDefaultEndSize; + float m_fDefaultModeASpeed; + float m_fDefaultModeASpeedVar; + CCPoint m_tDefaultPosVar; + ) + public: + RT_ADD( + void saveDefaults(void); + void loadDefaults(void); + void loadScaledDefaults(float); + + void calculateWorldSpace(); + + bool getDontCleanupOnFinish() const; + void setDontCleanupOnFinish(bool); + + bool getDynamicRotationIsDir() const; + void setDynamicRotationIsDir(bool); + + bool getEndRGBVarSync() const; + void setEndRGBVarSync(bool); + + float getFadeInTime() const; + float getFadeInTimeVar() const; + float getFadeOutTime() const; + float getFadeOutTimeVar() const; + float getFrictionPos() const; + float getFrictionPosVar() const; + float getFrictionRot() const; + float getFrictionRotVar() const; + float getFrictionSize() const; + float getFrictionSizeVar() const; + + bool getOrderSensitive() const; + + float getRespawn() const; + float getRespawnVar() const; + + bool getStartRGBVarSync() const; + bool getStartRadiusEqualToEnd() const; + bool getStartSizeEqualToEnd() const; + bool getStartSpinEqualToEnd() const; + + float getTimeElapsed(); + + bool getUseUniformColorMode() const; + + bool getWasRemoved() const; + + bool getUsingSchedule() const; + + + void setEndAlpha(float); + void setFadeInTime(float); + void setFadeInTimeVar(float); + void setFadeOutTime(float); + void setFadeOutTimeVar(float); + void setFrictionPos(float); + void setFrictionPosVar(float); + void setFrictionRot(float); + void setFrictionRotVar(float); + void setFrictionSize(float); + void setFrictionSizeVar(float); + + void setOrderSensitive(bool); + + void setRespawn(float); + void setRespawnVar(float); + + void setStartAlpha(float); + void setStartRGBVarSync(bool); + void setStartRadiusEqualToEnd(bool); + void setStartSizeEqualToEnd(bool); + void setStartSpinEqualToEnd(bool); + + void setUsingSchedule(bool); + + void setWasRemoved(bool); + + void toggleUniformColorMode(bool); + void updateVisible(); + + virtual void updateEmissionRate(); + + + ) + }; + class CCParticleSystemQuad : public CCParticleSystem + { + protected: + ccV3F_C4B_T2F_Quad *m_pQuads; // quads to be rendered + GLushort *m_pIndices; // indices + + #if CC_TEXTURE_ATLAS_USE_VAO + GLuint m_uVAOname; + #endif + + GLuint m_pBuffersVBO[2]; //0: vertex 1: indices + + public: + CCParticleSystemQuad(); + virtual ~CCParticleSystemQuad(); + + static CCParticleSystemQuad * create(const char *plistFile); + + void initIndices(); + + void initTexCoordsWithRect(const CCRect& rect); + + void setDisplayFrame(CCSpriteFrame *spriteFrame); + + void setTextureWithRect(CCTexture2D *texture, const CCRect& rect); + virtual bool initWithTotalParticles(unsigned int numberOfParticles, bool); + virtual void setTexture(CCTexture2D* texture); + virtual void updateQuadWithParticle(tCCParticle* particle, const CCPoint& newPosition); + virtual void postStep(); + virtual void draw(); + virtual void setBatchNode(CCParticleBatchNode* batchNode); + virtual void setTotalParticles(unsigned int tp); + void listenBackToForeground(CCObject *obj); + + static CCParticleSystemQuad * create(); + static CCParticleSystemQuad * create(const char*, bool); + static CCParticleSystemQuad * createWithTotalParticles(unsigned int numberOfParticles, bool); + + unsigned char getOpacity(); + void setOpacity(unsigned char); + + void updateTexCoords(); + + private: + #if CC_TEXTURE_ATLAS_USE_VAO + void setupVBOandVAO(); + #else + void setupVBO(); + #endif + bool allocMemory(); + }; + + + // CCApplication + class CCApplicationProtocol + { + public: + virtual ~CCApplicationProtocol() {} + + virtual bool applicationDidFinishLaunching() { return true; } + + virtual void applicationDidEnterBackground() {} + + virtual void applicationWillEnterForeground() {} + + RT_ADD( + virtual void applicationWillBecomeActive() {} + virtual void applicationWillResignActive() {} + virtual void trySaveGame(bool) {} + virtual void gameDidSave() {} + ) + + virtual void setAnimationInterval(double interval) {} + + virtual ccLanguageType getCurrentLanguage() { return kLanguageEnglish; } + + virtual TargetPlatform getTargetPlatform() { return kTargetWindows; } + + RT_ADD( virtual void openURL(const char* url) {} ) + }; + + class CCApplication : public CCApplicationProtocol + { + public: + CCApplication(); + virtual ~CCApplication(); + + virtual void setAnimationInterval(double interval) override; + + int run(); + + static CCApplication* sharedApplication(); + + virtual ccLanguageType getCurrentLanguage() override; + + virtual TargetPlatform getTargetPlatform() override; + + virtual void openURL(char const* url) override; + + protected: + static CCApplication * sm_pSharedApplication; + }; + + + // CCLabelBMFont + enum { + kCCLabelAutomaticWidth = -1, + }; + + class CCBMFontConfiguration : public CCObject + { + // XXX: Creating a public interface so that the bitmapFontArray[] is accessible + public://@public + // BMFont definitions + tCCFontDefHashElement *m_pFontDefDictionary; + + //! FNTConfig: Common Height Should be signed (issue #1343) + int m_nCommonHeight; + //! Padding + ccBMFontPadding m_tPadding; + //! atlas name + std::string m_sAtlasName; + //! values for kerning + tCCKerningHashElement *m_pKerningDictionary; + + // Character Set defines the letters that actually exist in the font + std::set *m_pCharacterSet; + public: + CCBMFontConfiguration(); + /** + * @js NA + * @lua NA + */ + virtual ~CCBMFontConfiguration(); + /** + * @js NA + * @lua NA + */ + const char * description(); + + /** allocates a CCBMFontConfiguration with a FNT file */ + static CCBMFontConfiguration * create(const char *FNTfile); + + /** initializes a BitmapFontConfiguration with a FNT file */ + bool initWithFNTfile(const char *FNTfile); + + inline const char* getAtlasName(){ return m_sAtlasName.c_str(); } + inline void setAtlasName(const char* atlasName) { m_sAtlasName = atlasName; } + + inline std::set* getCharacterSet() const { return m_pCharacterSet; } + private: + std::set* parseConfigFile(const char *controlFile); + void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition); + void parseInfoArguments(std::string line); + void parseCommonArguments(std::string line); + void parseImageFileName(std::string line, const char *fntFile); + void parseKerningEntry(std::string line); + void purgeKerningDictionary(); + void purgeFontDefDictionary(); + }; + + class CCLabelProtocol + { + public: + virtual void setString(const char *label) = 0; + + virtual const char* getString(void) = 0; + }; + + class CCLabelBMFont : public CCSpriteBatchNode, public CCLabelProtocol, public CCRGBAProtocol + { + public: + CCLabelBMFont(); + virtual ~CCLabelBMFont(); + static void purgeCachedData(); + + static CCLabelBMFont * create(const char *str, const char *fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset); + static CCLabelBMFont * create(const char *str, const char *fntFile, float width, CCTextAlignment alignment); + static CCLabelBMFont * create(const char *str, const char *fntFile, float width); + static CCLabelBMFont * create(const char *str, const char *fntFile); + + static CCLabelBMFont * create(); + + bool init(); + bool initWithString(const char *str, const char *fntFile, float width = kCCLabelAutomaticWidth, CCTextAlignment alignment = kCCTextAlignmentLeft, CCPoint imageOffset = CCPointZero); + + void createFontChars(); + // super method + virtual void setString(const char *newString); + virtual void setString(const char *newString, bool needUpdateLabel); + + virtual const char* getString(void); + virtual void setCString(const char *label); + virtual void setAnchorPoint(const CCPoint& var); + virtual void updateLabel(); + virtual void setAlignment(CCTextAlignment alignment); + virtual void setWidth(float width); + virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); + virtual void setScale(float scale); + virtual void setScaleX(float scaleX); + virtual void setScaleY(float scaleY); + + // CCRGBAProtocol + virtual bool isOpacityModifyRGB(); + virtual void setOpacityModifyRGB(bool isOpacityModifyRGB); virtual GLubyte getOpacity(); + virtual GLubyte getDisplayedOpacity(); + virtual void setOpacity(GLubyte opacity); + virtual void updateDisplayedOpacity(GLubyte parentOpacity); + virtual bool isCascadeOpacityEnabled(); + virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled); + virtual const ccColor3B& getColor(void); + virtual const ccColor3B& getDisplayedColor(); + virtual void setColor(const ccColor3B& color); + virtual void updateDisplayedColor(const ccColor3B& parentColor); + virtual bool isCascadeColorEnabled(); + virtual void setCascadeColorEnabled(bool cascadeColorEnabled); + + void setFntFile(const char* fntFile); + const char* getFntFile(); + inline CCBMFontConfiguration* getConfiguration() const { + return m_pConfiguration; + } + #if CC_LABELBMFONT_DEBUG_DRAW + virtual void draw(); + #endif // CC_LABELBMFONT_DEBUG_DRAW + + RT_ADD( + static CCLabelBMFont* createBatched(const char* str, const char* fntFile, CCArray*, int); + void limitLabelWidth(float width, float defaultScale, float minScale); + + int getExtraKerning() const; + void setExtraKerning(int); + + bool getIsBatched() const; + void setIsBatched(bool); + + cocos2d::CCArray* getTargetArray() const; + void setTargetArray(cocos2d::CCArray*); + + ) + + private: + char * atlasNameFromFntFile(const char *fntFile); + int kerningAmountForFirst(unsigned short first, unsigned short second); + float getLetterPosXLeft( CCSprite* characterSprite, float, bool); + float getLetterPosXRight( CCSprite* characterSprite, float, bool); + + protected: + virtual void setString(unsigned short *newString, bool needUpdateLabel); + // string to render + unsigned short* m_sString; + + // name of fntFile + std::string m_sFntFile; + + // initial string without line breaks + unsigned short* m_sInitialString; + std::string m_sInitialStringUTF8; + + // alignment of all lines + CCTextAlignment m_pAlignment; + // max width until a line break is added + float m_fWidth; + + CCBMFontConfiguration *m_pConfiguration; + + bool m_bLineBreakWithoutSpaces; + // offset of the texture atlas + CCPoint m_tImageOffset; + + // reused char + CCSprite *m_pReusedChar; + + // texture RGBA + GLubyte m_cDisplayedOpacity; + GLubyte m_cRealOpacity; + ccColor3B m_tDisplayedColor; + ccColor3B m_tRealColor; + bool m_bCascadeColorEnabled; + bool m_bCascadeOpacityEnabled; + /** conforms to CCRGBAProtocol protocol */ + bool m_bIsOpacityModifyRGB; + + RT_ADD( + bool m_bIsBatched; + CCArray* m_pTargetArray; + CCTexture2D* m_pSomeTexture; + void* m_pUnknown; // 2.2 addition, might be positioned somewhere else + ) + }; + + + // CCTextFieldTTF + class CCLabelTTF : public CCSprite, public CCLabelProtocol + { + public: + CCLabelTTF(); + virtual ~CCLabelTTF(); + const char* description(); + + static CCLabelTTF * create(const char *string, const char *fontName, float fontSize); + + static CCLabelTTF * create(const char *string, const char *fontName, float fontSize, + const CCSize& dimensions, CCTextAlignment hAlignment); + + static CCLabelTTF * create(const char *string, const char *fontName, float fontSize, + const CCSize& dimensions, CCTextAlignment hAlignment, + CCVerticalTextAlignment vAlignment); + + static CCLabelTTF * createWithFontDefinition(const char *string, ccFontDefinition &textDefinition); + + bool initWithString(const char *string, const char *fontName, float fontSize); + + bool initWithString(const char *string, const char *fontName, float fontSize, + const CCSize& dimensions, CCTextAlignment hAlignment); + + bool initWithString(const char *string, const char *fontName, float fontSize, + const CCSize& dimensions, CCTextAlignment hAlignment, + CCVerticalTextAlignment vAlignment); + + bool initWithStringAndTextDefinition(const char *string, ccFontDefinition &textDefinition); + + void setTextDefinition(ccFontDefinition *theDefinition); + + ccFontDefinition * getTextDefinition(); + + + + void enableShadow(const CCSize &shadowOffset, float shadowOpacity, float shadowBlur, bool mustUpdateTexture = true); + + void disableShadow(bool mustUpdateTexture = true); + + void enableStroke(const ccColor3B &strokeColor, float strokeSize, bool mustUpdateTexture = true); + + void disableStroke(bool mustUpdateTexture = true); + + void setFontFillColor(const ccColor3B &tintColor, bool mustUpdateTexture = true); + + + bool init(); + + static CCLabelTTF * create(); + + virtual void setString(const char *label); + virtual const char* getString(void); + + CCTextAlignment getHorizontalAlignment() { + return m_hAlignment; + } + void setHorizontalAlignment(CCTextAlignment alignment) { + if (alignment != m_hAlignment) + { + m_hAlignment = alignment; + + // Force update + if (std::string(m_string).size() > 0) + { + this->updateTexture(); + } + } + } + + CCVerticalTextAlignment getVerticalAlignment() { + return m_vAlignment; + } + void setVerticalAlignment(CCVerticalTextAlignment verticalAlignment) { + if (verticalAlignment != m_vAlignment) + { + m_vAlignment = verticalAlignment; + + // Force update + if (std::string(m_string).size() > 0) + { + this->updateTexture(); + } + } + } + + CCSize getDimensions() { + return m_tDimensions; + } + void setDimensions(const CCSize &dim) { + if (dim.width != m_tDimensions.width || dim.height != m_tDimensions.height) + { + m_tDimensions = dim; + + // Force update + if (std::string(m_string).size() > 0) + { + this->updateTexture(); + } + } + } + + float getFontSize() { + return m_fFontSize; + } + void setFontSize(float fontSize) { + if (m_fFontSize != fontSize) + { + m_fFontSize = fontSize; + + // Force update + if (std::string(m_string).size() > 0) + { + this->updateTexture(); + } + } + } + + const char* getFontName(); + void setFontName(const char *fontName); + + private: + bool updateTexture(); + + protected: + void _updateWithTextDefinition(ccFontDefinition & textDefinition, bool mustUpdateTexture = true); + ccFontDefinition _prepareTextDefinition(bool adjustForResolution = false); + + CCSize m_tDimensions; + CCTextAlignment m_hAlignment; + CCVerticalTextAlignment m_vAlignment; + std::string * m_pFontName; + float m_fFontSize; + std::string m_string; + + bool m_shadowEnabled; + CCSize m_shadowOffset; + float m_shadowOpacity; + float m_shadowBlur; + + + bool m_strokeEnabled; + ccColor3B m_strokeColor; + float m_strokeSize; + + ccColor3B m_textFillColor; + }; + + // is this really pimpl? + class CCIMEDelegate; + class CCIMEDispatcher + { + public: + ~CCIMEDispatcher(); + + static CCIMEDispatcher* sharedDispatcher(); + + // /** + // @brief Releases all CCIMEDelegates from the shared dispatcher. + // */ + // static void purgeSharedDispatcher(); + + void dispatchInsertText(const char * pText, int nLen, cocos2d::enumKeyCodes); + + void dispatchDeleteBackward(); + + void dispatchDeleteForward(); + + bool hasDelegate(); + + const char * getContentText(); + + ////////////////////////////////////////////////////////////////////////// + // dispatch keyboard notification + ////////////////////////////////////////////////////////////////////////// + void dispatchKeyboardWillShow(CCIMEKeyboardNotificationInfo& info); + void dispatchKeyboardDidShow(CCIMEKeyboardNotificationInfo& info); + void dispatchKeyboardWillHide(CCIMEKeyboardNotificationInfo& info); + void dispatchKeyboardWillHide(); + void dispatchKeyboardDidHide(CCIMEKeyboardNotificationInfo& info); + + protected: + friend class CCIMEDelegate; + + void addDelegate(CCIMEDelegate * pDelegate); + + bool attachDelegateWithIME(CCIMEDelegate * pDelegate); + bool detachDelegateWithIME(CCIMEDelegate * pDelegate); + + void removeDelegate(CCIMEDelegate * pDelegate); + + private: + CCIMEDispatcher(); + + class Impl; + Impl * m_pImpl; + }; + + class CCIMEDelegate + { + public: + virtual ~CCIMEDelegate(); + + virtual bool attachWithIME(); + virtual bool detachWithIME(); + + protected: + friend class CCIMEDispatcher; + + virtual bool canAttachWithIME() { return false; } + virtual void didAttachWithIME() {} + + virtual bool canDetachWithIME() { return false; } + + virtual void didDetachWithIME() {} + + virtual void insertText(const char * text, int len, cocos2d::enumKeyCodes) {CC_UNUSED_PARAM(text);CC_UNUSED_PARAM(len);} + + virtual void deleteBackward() {} + + virtual const char * getContentText() { return 0; } + + ////////////////////////////////////////////////////////////////////////// + // keyboard show/hide notification + ////////////////////////////////////////////////////////////////////////// + virtual void keyboardWillShow(CCIMEKeyboardNotificationInfo& info) {CC_UNUSED_PARAM(info);} + virtual void keyboardDidShow(CCIMEKeyboardNotificationInfo& info) {CC_UNUSED_PARAM(info);} + virtual void keyboardWillHide(CCIMEKeyboardNotificationInfo& info) {CC_UNUSED_PARAM(info);} + virtual void keyboardDidHide(CCIMEKeyboardNotificationInfo& info) {CC_UNUSED_PARAM(info);} + + virtual void deleteForward(); + + protected: + CCIMEDelegate(); + }; + + class CCTextFieldTTF; + class CCTextFieldDelegate + { + public: + virtual bool onTextFieldAttachWithIME(CCTextFieldTTF * sender) + { + CC_UNUSED_PARAM(sender); + return false; + } + + virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * sender) + { + CC_UNUSED_PARAM(sender); + return false; + } + + virtual bool onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen, cocos2d::enumKeyCodes) + { + CC_UNUSED_PARAM(sender); + CC_UNUSED_PARAM(text); + CC_UNUSED_PARAM(nLen); + return false; + } + + virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * sender, const char * delText, int nLen) + { + CC_UNUSED_PARAM(sender); + CC_UNUSED_PARAM(delText); + CC_UNUSED_PARAM(nLen); + return false; + } + + virtual bool onDraw(CCTextFieldTTF * sender) + { + CC_UNUSED_PARAM(sender); + return false; + } + + RT_ADD( + virtual void textChanged() {} + ) + }; + + class CCTextFieldTTF : public CCLabelTTF, public CCIMEDelegate + { + public: + CCTextFieldTTF(); + virtual ~CCTextFieldTTF(); + + //char * description(); + + static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize); + static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); + bool initWithPlaceHolder(const char *placeholder, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize); + bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); + + virtual bool attachWithIME(); + + virtual bool detachWithIME(); + + ////////////////////////////////////////////////////////////////////////// + // properties + ////////////////////////////////////////////////////////////////////////// + + CC_SYNTHESIZE_NV(CCTextFieldDelegate *, m_pDelegate, Delegate); + CC_SYNTHESIZE_READONLY(int, m_nCharCount, CharCount); + virtual const ccColor3B& getColorSpaceHolder(); + virtual void setColorSpaceHolder(const ccColor3B& color); + + // input text property + public: + virtual void setString(const char *text); + virtual const char* getString(void); + protected: + std::string * m_pInputText; + + // place holder text property + // place holder text displayed when there is no text in the text field. + public: + virtual void setPlaceHolder(const char * text); + virtual const char * getPlaceHolder(void); + protected: + std::string * m_pPlaceHolder; + ccColor3B m_ColorSpaceHolder; + public: + virtual void setSecureTextEntry(bool value); + virtual bool isSecureTextEntry(); + protected: + bool m_bSecureTextEntry; + protected: + + virtual void draw(); + + ////////////////////////////////////////////////////////////////////////// + // CCIMEDelegate interface + ////////////////////////////////////////////////////////////////////////// + + virtual bool canAttachWithIME(); + virtual bool canDetachWithIME(); + virtual void insertText(const char * text, int len, cocos2d::enumKeyCodes); + virtual void deleteBackward(); + virtual const char * getContentText(); + private: + class LengthStack; + LengthStack * m_pLens; + }; + + + // CCMotionStreak + class CCMotionStreak : public CCNodeRGBA, public CCTextureProtocol + { + public: + CCMotionStreak(); + virtual ~CCMotionStreak(); + + static CCMotionStreak* create( + float fade, float minSeg, float stroke, ccColor3B const& color, char const* path + ); + static CCMotionStreak* create( + float fade, float minSeg, float stroke, ccColor3B const& color, CCTexture2D* texture + ); + + bool initWithFade( + float fade, float minSeg, float stroke, ccColor3B const& color, char const* path + ); + bool initWithFade( + float fade, float minSeg, float stroke, ccColor3B const& color, CCTexture2D* texture + ); + + void tintWithColor(ccColor3B colors); + + void reset(); + + virtual void setPosition(CCPoint const& position); + virtual void draw(); + virtual void update(float delta); + + virtual CCTexture2D* getTexture(void); + virtual void setTexture(CCTexture2D* texture); + virtual void setBlendFunc(ccBlendFunc blendFunc); + virtual ccBlendFunc getBlendFunc(void); + virtual GLubyte getOpacity(void); + virtual void setOpacity(GLubyte opacity); + virtual void setOpacityModifyRGB(bool bValue); + virtual bool isOpacityModifyRGB(void); + + RT_ADD( + void resumeStroke(); + void stopStroke(); + + void enableRepeatMode(float); + + bool getDontOpacityFade() const; + void setDontOpacityFade(bool); + + float getM_fMaxSeg() const; + void setM_fMaxSeg(float); + + void setStroke(float); + void updateFade(float); + ) + + inline bool isFastMode() { + return m_bFastMode; + } + + inline void setFastMode(bool bFastMode) { + m_bFastMode = bFastMode; + } + + inline bool isStartingPositionInitialized() { + return m_bStartingPositionInitialized; + } + + inline void setStartingPositionInitialized(bool bStartingPositionInitialized) { + m_bStartingPositionInitialized = bStartingPositionInitialized; + } + + protected: + bool m_bFastMode; + bool m_bStartingPositionInitialized; + bool m_bStroke; + CCTexture2D* m_pTexture; + ccBlendFunc m_tBlendFunc; + CCPoint m_tPositionR; + + float m_fStroke; + float m_fFadeDelta; + float m_fMinSeg; + + unsigned int m_uMaxPoints; + unsigned int m_uNuPoints; + unsigned int m_uPreviousNuPoints; + + CCPoint* m_pPointVertexes; + float* m_pPointState; + + ccVertex2F* m_pVertices; + GLubyte* m_pColorPointer; + ccTex2F* m_pTexCoords; + + RT_ADD( + bool m_bRepeatMode; + float m_fRepeatSpeed; + float m_fRepeatTime; + bool m_idk; + float m_fMaxSeg; + bool m_bDontOpacityFade; + ) + }; + + + // CCTouchDispatcher + class CCTouchHandler : public CCObject + { + public: + inline CCTouchHandler() = default; + virtual ~CCTouchHandler(void); + + CCTouchDelegate* getDelegate(); + void setDelegate(CCTouchDelegate *pDelegate); + + int getPriority(void); + void setPriority(int nPriority); + + int getEnabledSelectors(void); + void setEnalbedSelectors(int nValue); + + virtual bool initWithDelegate(CCTouchDelegate *pDelegate, int nPriority); + + public: + static CCTouchHandler* handlerWithDelegate(CCTouchDelegate *pDelegate, int nPriority); + + public: + CCTouchDelegate *m_pDelegate; + int m_nPriority; + int m_nEnabledSelectors; + }; + + class EGLTouchDelegate + { + public: + virtual void touchesBegan(CCSet* touches, CCEvent* pEvent) = 0; + virtual void touchesMoved(CCSet* touches, CCEvent* pEvent) = 0; + virtual void touchesEnded(CCSet* touches, CCEvent* pEvent) = 0; + virtual void touchesCancelled(CCSet* touches, CCEvent* pEvent) = 0; + virtual ~EGLTouchDelegate() {} + }; + + class CCTouchDispatcher : public CCObject, public EGLTouchDelegate + { + public: + ~CCTouchDispatcher(); + bool init(void); + CCTouchDispatcher() + : m_pTargetedHandlers(NULL) + , m_pStandardHandlers(NULL) + , m_pHandlersToAdd(NULL) + , m_pHandlersToRemove(NULL) + {} + + public: + bool isDispatchEvents(void); + void setDispatchEvents(bool bDispatchEvents); + + void addStandardDelegate(CCTouchDelegate *pDelegate, int nPriority); + + void addTargetedDelegate(CCTouchDelegate *pDelegate, int nPriority, bool bSwallowsTouches); + + void removeDelegate(CCTouchDelegate *pDelegate); + + void removeAllDelegates(void); + + void setPriority(int nPriority, CCTouchDelegate *pDelegate); + void touches(CCSet *pTouches, CCEvent *pEvent, unsigned int uIndex); + virtual void touchesBegan(CCSet* touches, CCEvent* pEvent); + virtual void touchesMoved(CCSet* touches, CCEvent* pEvent); + virtual void touchesEnded(CCSet* touches, CCEvent* pEvent); + virtual void touchesCancelled(CCSet* touches, CCEvent* pEvent); + + public: + CCTouchHandler* findHandler(CCTouchDelegate *pDelegate); + + void addPrioTargetedDelegate(cocos2d::CCTouchDelegate*, int, bool); + bool isUsingForcePrio(); + void registerForcePrio(cocos2d::CCObject*, int); + void unregisterForcePrio(cocos2d::CCObject*); + + private: + RT_ADD( + void incrementForcePrio(int priority); + void decrementForcePrio(int priority); + ) + + protected: + void forceRemoveDelegate(CCTouchDelegate *pDelegate); + void forceAddHandler(CCTouchHandler *pHandler, CCArray* pArray); + void forceRemoveAllDelegates(void); + void rearrangeHandlers(CCArray* pArray); + CCTouchHandler* findHandler(CCArray* pArray, CCTouchDelegate *pDelegate); + + public: + CCArray* m_pTargetedHandlers; + CCArray* m_pStandardHandlers; + + bool m_bLocked; + bool m_bToAdd; + bool m_bToRemove; + CCArray* m_pHandlersToAdd; + struct _ccCArray *m_pHandlersToRemove; + bool m_bToQuit; + bool m_bDispatchEvents; + + // 4, 1 for each type of event + struct ccTouchHandlerHelperData m_sHandlerHelperData[ccTouchMax]; + + protected: + // 2.2 changes + + CC_SYNTHESIZE_NV(int, m_forcePrio, ForcePrio); + void* m_unknown; + CC_SYNTHESIZE_NV(int, m_targetPrio, TargetPrio); + }; + + + // extension + namespace extension + { + // http stuff + class CCHttpClient; + class CCHttpResponse; + typedef void (CCObject::*SEL_HttpResponse)(CCHttpClient* client, CCHttpResponse* response); + + class CCHttpRequest : public CCObject + { + public: + /** Use this enum type as param in setReqeustType(param) */ + typedef enum + { + kHttpGet, + kHttpPost, + kHttpPut, + kHttpDelete, + kHttpUnkown, + } HttpRequestType; + + CCHttpRequest() : _url(), _requestData(), _tag() + { + _requestType = kHttpUnkown; + _pTarget = NULL; + _pSelector = NULL; + _pUserData = NULL; + }; + + virtual ~CCHttpRequest() + { + if (_pTarget) + { + _pTarget->release(); + } + }; + + CCObject* autorelease(void) + { + CCAssert(false, "HttpResponse is used between network thread and ui thread \ + therefore, autorelease is forbidden here"); + return NULL; + } + + // setter/getters for properties + + inline void setRequestType(HttpRequestType type) + { + _requestType = type; + }; + inline HttpRequestType getRequestType() + { + return _requestType; + }; + + inline void setUrl(const char* url) + { + _url = url; + }; + inline const char* getUrl() + { + return _url.c_str(); + }; + + inline void setRequestData(const char* buffer, unsigned int len) + { + auto vec = std::vector(_requestData); + vec.assign(buffer, buffer + len); + _requestData = std::vector(vec); + }; + inline char* getRequestData() + { + return &(_requestData.front()); + } + inline int getRequestDataSize() + { + return std::vector(_requestData).size(); + } + + inline void setTag(const char* tag) + { + _tag = tag; + }; + inline const char* getTag() + { + return _tag.c_str(); + }; + + inline void setUserData(void* pUserData) + { + _pUserData = pUserData; + }; + inline void* getUserData() + { + return _pUserData; + }; + + CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(CCObject* pTarget, SEL_CallFuncND pSelector) + { + setResponseCallback(pTarget, (SEL_HttpResponse) pSelector); + } + + inline void setResponseCallback(CCObject* pTarget, SEL_HttpResponse pSelector) + { + _pTarget = pTarget; + _pSelector = pSelector; + + if (_pTarget) + { + _pTarget->retain(); + } + } + inline CCObject* getTarget() + { + return _pTarget; + } + + class _prxy + { + public: + _prxy( SEL_HttpResponse cb ) :_cb(cb) {} + ~_prxy(){}; + operator SEL_HttpResponse() const { return _cb; } + CC_DEPRECATED_ATTRIBUTE operator SEL_CallFuncND() const { return (SEL_CallFuncND) _cb; } + protected: + SEL_HttpResponse _cb; + }; + + inline _prxy getSelector() + { + return _prxy(_pSelector); + } + + inline void setHeaders(std::vector pHeaders) + { + _headers=pHeaders; + } + + inline std::vector getHeaders() + { + return _headers; + } + + + protected: + // properties + HttpRequestType _requestType; /// kHttpRequestGet, kHttpRequestPost or other enums + std::string _url; /// target url that this request is sent to + std::vector _requestData; /// used for POST + std::string _tag; /// user defined tag, to identify different requests in response callback + CCObject* _pTarget; /// callback target of pSelector function + SEL_HttpResponse _pSelector; /// callback function, e.g. MyLayer::onHttpResponse(CCHttpClient *sender, CCHttpResponse * response) + void* _pUserData; /// You can add your customed data here + std::vector _headers; /// custom http headers + + RT_ADD( + int _requestTypeGJ; + bool _shouldCancel; + int _downloadProgress; + int _readTimeout; + ) + }; + + class CCHttpResponse : public CCObject + { + public: + CCHttpResponse(CCHttpRequest* request) : _responseData(), _errorBuffer() + { + _pHttpRequest = request; + if (_pHttpRequest) + { + _pHttpRequest->retain(); + } + + _succeed = false; + } + + virtual ~CCHttpResponse() + { + if (_pHttpRequest) + { + _pHttpRequest->release(); + } + } + + CCObject* autorelease(void) + { + CCAssert(false, "HttpResponse is used between network thread and ui thread \ + therefore, autorelease is forbidden here"); + return NULL; + } + + // getters, will be called by users + + inline CCHttpRequest* getHttpRequest() + { + return _pHttpRequest; + } + + inline bool isSucceed() + { + return _succeed; + }; + + inline std::vector* getResponseData() + { + return &_responseData; + } + + inline std::vector* getResponseHeader() + { + return &_responseHeader; + } + + inline int getResponseCode() + { + return _responseCode; + } + + inline const char* getErrorBuffer() + { + return _errorBuffer.c_str(); + } + + // setters, will be called by CCHttpClient + // users should avoid invoking these methods + + + inline void setSucceed(bool value) + { + _succeed = value; + }; + + + inline void setResponseData(std::vector* data) + { + _responseData = *data; + } + + inline void setResponseHeader(std::vector* data) + { + _responseHeader = *data; + } + + + inline void setResponseCode(int value) + { + _responseCode = value; + } + + + inline void setErrorBuffer(const char* value) + { + _errorBuffer = std::string(value); + }; + + protected: + bool initWithRequest(CCHttpRequest* request); + + // properties + CCHttpRequest* _pHttpRequest; /// the corresponding HttpRequest pointer who leads to this response + bool _succeed; /// to indecate if the http reqeust is successful simply + std::vector _responseData; /// the returned raw data. You can also dump it as a string + std::vector _responseHeader; /// the returned raw header data. You can also dump it as a string + int _responseCode; /// the status code returned from libcurl, e.g. 200, 404 + std::string _errorBuffer; /// if _responseCode != 200, please read _errorBuffer to find the reason + }; + + class CCHttpClient : public CCObject + { + public: + static CCHttpClient *getInstance(); + + static void destroyInstance(); + + void send(CCHttpRequest* request); + + + inline void setTimeoutForConnect(int value) {_timeoutForConnect = value;}; + + inline int getTimeoutForConnect() {return _timeoutForConnect;} + + + inline void setTimeoutForRead(int value) {_timeoutForRead = value;}; + + + inline int getTimeoutForRead() {return _timeoutForRead;}; + + private: + CCHttpClient(); + virtual ~CCHttpClient(); + bool init(void); + + bool lazyInitThreadSemphore(); + void dispatchResponseCallbacks(float delta); + + private: + int _timeoutForConnect; + int _timeoutForRead; + + // std::string reqId; + }; + + + // misc + class CCScale9Sprite : public CCNodeRGBA + { + public: + CCScale9Sprite(); + virtual ~CCScale9Sprite(); + + public: + CC_SYNTHESIZE_READONLY_NV(CCSize, m_originalSize, OriginalSize); + + CC_PROPERTY(CCSize, m_preferredSize, PreferredSize); + CC_PROPERTY(CCRect, m_capInsets, CapInsets); + CC_PROPERTY(float, m_insetLeft, InsetLeft); + CC_PROPERTY(float, m_insetTop, InsetTop); + CC_PROPERTY(float, m_insetRight, InsetRight); + CC_PROPERTY(float, m_insetBottom, InsetBottom); + + protected: + bool m_bSpritesGenerated; + CCRect m_spriteRect; + bool m_bSpriteFrameRotated; + CCRect m_capInsetsInternal; + bool m_positionsAreDirty; + + CCSpriteBatchNode* _scale9Image; + CCSprite* _topLeft; + CCSprite* _top; + CCSprite* _topRight; + CCSprite* _left; + CCSprite* _centre; + CCSprite* _right; + CCSprite* _bottomLeft; + CCSprite* _bottom; + CCSprite* _bottomRight; + + bool _opacityModifyRGB; + GLubyte _opacity; + ccColor3B _color; + + void updateCapInset(); + void updatePositions(); + + public: + virtual void setContentSize(const CCSize & size); + virtual void visit(); + + virtual bool init(); + + virtual bool initWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, bool rotated, CCRect capInsets); + virtual bool initWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, CCRect capInsets); + virtual bool initWithFile(const char* file, CCRect rect, CCRect capInsets); + + static CCScale9Sprite* create(const char* file, CCRect rect, CCRect capInsets); + + virtual bool initWithFile(const char* file, CCRect rect); + + static CCScale9Sprite* create(const char* file, CCRect rect); + + virtual bool initWithFile(CCRect capInsets, const char* file); + + static CCScale9Sprite* create(CCRect capInsets, const char* file); + + virtual bool initWithFile(const char* file); + + static CCScale9Sprite* create(const char* file); + + virtual bool initWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets); + + static CCScale9Sprite* createWithSpriteFrame(CCSpriteFrame* spriteFrame, CCRect capInsets); + virtual bool initWithSpriteFrame(CCSpriteFrame* spriteFrame); + + static CCScale9Sprite* createWithSpriteFrame(CCSpriteFrame* spriteFrame); + + virtual bool initWithSpriteFrameName(const char*spriteFrameName, CCRect capInsets); + + static CCScale9Sprite* createWithSpriteFrameName(const char*spriteFrameName, CCRect capInsets); + + virtual bool initWithSpriteFrameName(const char*spriteFrameName); + + static CCScale9Sprite* createWithSpriteFrameName(const char*spriteFrameName); + + CCScale9Sprite* resizableSpriteWithCapInsets(CCRect capInsets); + + static CCScale9Sprite* create(); + + // optional + + virtual void setOpacityModifyRGB(bool bValue); + + virtual bool isOpacityModifyRGB(void); + virtual void setOpacity(GLubyte opacity); + virtual GLubyte getOpacity(); + virtual void setColor(const ccColor3B& color); + virtual const ccColor3B& getColor(); + + virtual bool updateWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, bool rotated, CCRect capInsets); + + virtual void setSpriteFrame(CCSpriteFrame * spriteFrame); + + virtual void updateDisplayedOpacity(GLubyte parentOpacity); + virtual void updateDisplayedColor(const cocos2d::ccColor3B& parentColor); + }; + + + class ColorPickerDelegate + { + public: + virtual void colorValueChanged(ccColor3B) {} + }; + } +} diff --git a/broma_ida/types/enums.hpp b/broma_ida/types/enums.hpp new file mode 100644 index 0000000..74aeff3 --- /dev/null +++ b/broma_ida/types/enums.hpp @@ -0,0 +1,786 @@ +// taken from http://github.com/geode-sdk/geode/blob/main/loader/include/Geode/Enums.hpp + +// thanks pie +enum class SearchType { + Search = 0, + Downloaded = 1, + MostLiked = 2, + Trending = 3, + Recent = 4, + UsersLevels = 5, + Featured = 6, + Magic = 7, + Sends = 8, + MapPack = 9, + MapPackOnClick = 10, + Awarded = 11, + Followed = 12, + Friends = 13, + Users = 14, + LikedGDW = 15, + HallOfFame = 16, + FeaturedGDW = 17, + Similar = 18, + Type19 = 19, + TopListsUnused = 20, + DailySafe = 21, + WeeklySafe = 22, + EventSafe = 23, + Reported = 24, + LevelListsOnClick = 25, + Type26 = 26, + Sent = 27, + MyLevels = 98, + SavedLevels = 99, + FavouriteLevels = 100, + SmartTemplates = 101, + MyLists = 102, + FavouriteLists = 103 +}; + +enum class GameObjectType { + Solid = 0, + Hazard = 2, + InverseGravityPortal = 3, + NormalGravityPortal = 4, + ShipPortal = 5, + CubePortal = 6, + Decoration = 7, + YellowJumpPad = 8, + PinkJumpPad = 9, + GravityPad = 10, + YellowJumpRing = 11, + PinkJumpRing = 12, + GravityRing = 13, + InverseMirrorPortal = 14, + NormalMirrorPortal = 15, + BallPortal = 16, + RegularSizePortal = 17, + MiniSizePortal = 18, + UfoPortal = 19, + Modifier = 20, + Breakable = 21, + SecretCoin = 22, + DualPortal = 23, + SoloPortal = 24, + Slope = 25, + WavePortal = 26, + RobotPortal = 27, + TeleportPortal = 28, + GreenRing = 29, + Collectible = 30, + UserCoin = 31, + DropRing = 32, + SpiderPortal = 33, + RedJumpPad = 34, + RedJumpRing = 35, + CustomRing = 36, + DashRing = 37, + GravityDashRing = 38, + CollisionObject = 39, + Special = 40, + SwingPortal = 41, + GravityTogglePortal = 42, + SpiderOrb = 43, + SpiderPad = 44, + TeleportOrb = 46, + AnimatedHazard = 47, +}; + +enum class GJGameEvent { + None = 0, + TinyLanding = 1, + FeatherLanding = 2, + SoftLanding = 3, + NormalLanding = 4, + HardLanding = 5, + HitHead = 6, + OrbTouched = 7, + OrbActivated = 8, + PadActivated = 9, + GravityInverted = 10, + GravityRestored = 11, + NormalJump = 12, + RobotBoostStart = 13, + RobotBoostStop = 14, + UFOJump = 15, + ShipBoostStart = 16, + ShipBoostEnd = 17, + SpiderTeleport = 18, + BallSwitch = 19, + SwingSwitch = 20, + WavePush = 21, + WaveRelease = 22, + DashStart = 23, + DashStop = 24, + Teleported = 25, + PortalNormal = 26, + PortalShip = 27, + PortalBall = 28, + PortalUFO = 29, + PortalWave = 30, + PortalRobot = 31, + PortalSpider = 32, + PortalSwing = 33, + YellowOrb = 34, + PinkOrb = 35, + RedOrb = 36, + GravityOrb = 37, + GreenOrb = 38, + DropOrb = 39, + CustomOrb = 40, + DashOrb = 41, + GravityDashOrb = 42, + SpiderOrb = 43, + TeleportOrb = 44, + YellowPad = 45, + PinkPad = 46, + RedPad = 47, + GravityPad = 48, + SpiderPad = 49, + PortalGravityFlip = 50, + PortalGravityNormal = 51, + PortalGravityInvert = 52, + PortalFlip = 53, + PortalUnFlip = 54, + PortalNormalScale = 55, + PortalMiniScale = 56, + PortalDualOn = 57, + PortalDualOff = 58, + PortalTeleport = 59, + Checkpoint = 60, + DestroyBlock = 61, + UserCoin = 62, + PickupItem = 63, + CheckpointRespawn = 64, + FallLow = 65, + FallMed = 66, + FallHigh = 67, + FallVHigh = 68, + JumpPush = 69, + JumpRelease = 70, + LeftPush = 71, + LeftRelease = 72, + RightPush = 73, + RightRelease = 74, + PlayerReversed = 75, + FallSpeedLow = 76, + FallSpeedMed = 77, + FallSpeedHigh = 78 +}; + +enum class PulseEffectType { +}; +enum class TouchTriggerType { +}; +enum class PlayerButton { + Jump = 1, + Left = 2, + Right = 3, +}; +enum class GhostType { +}; +enum class TableViewCellEditingStyle { +}; +enum class UserListType { + Friends = 0, + Blocked = 1, +}; +enum class GJErrorCode { + NotFound = -1, + UpdateApp = 3 +}; +enum class AccountError { + EmailsDoNotMatch = -99, + AlreadyLinkedToDifferentSteamAccount = -13, + AccountDisabled = -12, + AlreadyLinkedToDifferentAccount = -10, + TooShortLessThan3 = -9, + TooShortLessThan6 = -8, + PasswordsDoNotMatch = -7, + InvalidEmail = -6, + InvalidPassword = -5, + InvalidUsername = -4, + AlreadyUsedEmail = -3, + AlreadyUsedUsername = -2 +}; +enum class GJSongError { + DownloadSongFailed = 1, + DownloadSFXFailed = 2 +}; +enum class LikeItemType { + Unknown = 0, + Level = 1, + Comment = 2, + AccountComment = 3, + LevelList = 4 +}; + +enum class CommentError { +}; +enum class BackupAccountError { + BackupOrSyncFailed = -3, + LoginFailed = -2 +}; +enum class GJMusicAction { + DownloadOrUpdate = 2, + UpdateSFXLibrary = 4, + UpdateMusicLibrary = 6 +}; +enum class CellAction {}; +enum class GJActionCommand {}; +enum class DifficultyIconType { + ShortText = 0, + DefaultText = 1, + NoText = 2 +}; +enum class GauntletType { + Fire = 0, + Ice = 2, + Poison = 3, + Shadow = 4, + Lava = 5, + Bonus = 6, + Chaos = 7, + Demon = 8, + Time = 9, + Crystal = 0xA, + Magic = 0xB, + Spike = 0xC, + Monster = 0xD, + Doom = 0xE, + Death = 0xF, + Forest = 0x10, + Rune = 0x11, + Force = 0x12, + Spooky = 0x13, + Dragon = 0x14, + Water = 0x15, + Haunted = 0x16, + Acid = 0x17, + Witch = 0x18, + Power = 0x19, + Potion = 0x1A, + Snake = 0x1B, + Toxic = 0x1C, + Halloween = 0x1D, + Treasure = 0x1E, + Ghost = 0x1F, + Spider = 0x20, + Gem = 0x21, + Inferno = 0x22, + Portal = 0x23, + Strange = 0x24, + Fantasy = 0x25, + Christmas = 0x26, + Surprise = 0x27, + Mystery = 0x28, + Cursed = 0x29, + Cyborg = 0x2A, + Castle = 0x2B, + Grave = 0x2C, + Temple = 0x2D, + World = 0x2E, + Galaxy = 0x2F, + Universe = 0x30, + Discord = 0x31, + Split = 0x32 +}; +enum class GJMPErrorCode {}; +enum class GJTimedLevelType { + Daily = 0, + Weekly = 1, + Event = 2 +}; +enum class SongSelectType { + Default = 0, + Custom = 1 +}; +enum class AudioTargetType {}; +enum class FMODReverbPreset { + Generic = 0, + PaddedCell = 1, + Room = 2, + Bathroom = 3, + Livingroom = 4, + Stoneroom = 5, + Auditorium = 6, + ConvertHall = 7, + Cave = 8, + Arena = 9, + Hangar = 0xA, + CarpettedHallway = 0xB, + Hallway = 0xC, + StoneCorridor = 0xD, + Alley = 0xE, + Forest = 0xF, + City = 0x10, + Mountains = 0x11, + Quarry = 0x12, + Plain = 0x13, + ParkingLot = 0x14, + SewerPipe = 0x15, + Underwater = 0x16 +}; +enum class DemonDifficultyType { + HardDemon = 0, + EasyDemon = 3, + MediumDemon = 4, + InsaneDemon = 5, + ExtremeDemon = 6 +}; +enum class PlayerCollisionDirection { + Top = 0, + Bottom = 1, + Left = 2, + Right = 3 +}; +enum class ChestSpriteState {}; +enum class FormatterType {}; +enum class AudioModType {}; +enum class FMODQueuedMusic {}; +enum class GJAreaActionType {}; +enum class GJSmartDirection {}; +enum class SmartBlockType {}; +enum class TouchTriggerControl {}; +enum class AudioSortType {}; +enum class spriteMode {}; +enum class GJAssetType {}; +enum class CommentKeyType { + Level = 0, + User = 1, + LevelList = 2 +}; +enum class LevelLeaderboardMode { + Time = 0, + Points = 1 +}; +enum class StatKey {}; +enum class TextStyleType { + Colored = 1, + Instant = 2, + Shake = 3, + Delayed = 4 +}; +enum class InputValueType {}; +enum class GJInputStyle {}; +enum class GJDifficultyName { + Short = 0, + Long = 1 +}; +enum class GJFeatureState { + None = 0, + Featured = 1, + Epic = 2, + Legendary = 3, + Mythic = 4 +}; +enum class GJKeyGroup {}; +enum class GJKeyCommand {}; +enum class SelectSettingType {}; +enum class gjParticleValue { + MaxParticles = 1, + Duration = 2, + Lifetime = 3, + PlusMinus1 = 4, + Emission = 5, + Angle = 6, + PlusMinus2 = 7, + Speed = 8, + PlusMinus3 = 9, + PosVarX = 0xA, + PosVarY = 0xB, + GravityX = 0xC, + GravityY = 0xD, + AccelRad = 0xE, + PlusMinus4 = 0xF, + AccelTan = 0x10, + PlusMinus5 = 0x11, + StartSize = 0x12, + PlusMinus6 = 0x13, + EndSize = 0x14, + PlusMinus7 = 0x15, + StartSpin = 0x16, + PlusMinus8 = 0x17, + EndSpin = 0x18, + PlusMinus9 = 0x19, + StartR = 0x1A, + PlusMinus10 = 0x1B, + StartG = 0x1C, + PlusMinus11 = 0x1D, + StartB = 0x1E, + PlusMinus12 = 0x1F, + StartA = 0x20, + PlusMinus13 = 0x21, + EndR = 0x22, + PlusMinus14 = 0x23, + EndG = 0x24, + PlusMinus15 = 0x25, + EndB = 0x26, + PlusMinus16 = 0x27, + EndA = 0x28, + PlusMinus17 = 0x29, + FadeIn = 0x2A, + PlusMinus18 = 0x2B, + FadeOut = 0x2C, + PlusMinus19 = 0x2D, + FrictionP = 0x2E, + PlusMinus20 = 0x2F, + Respawn = 0x30, + PlusMinus21 = 0x31, + StartRad = 0x32, + PlusMinus22 = 0x33, + EndRad = 0x34, + PlusMinus23 = 0x35, + RotSec = 0x36, + PlusMinus24 = 0x37, + FrictionS = 0x45, + PlusMinus25 = 0x46, + FrictionR = 0x47, + PlusMinus26 = 0x48 +}; +enum class ColorSelectType {}; +enum class AudioGuidelinesType { + GuidelineCreator = 0, + BPMFinder = 1 +}; +enum class SmartBrowseFilter {}; +enum class GJUITouchEvent {}; +enum class ObjectScaleType { + XY = 0, + X = 1, + Y = 2 +}; + +enum class CommentType { + Level = 0, + Account = 1, +}; + +enum class BoomListType { + Default = 0x0, + User = 0x2, + Stats = 0x3, + Achievement = 0x4, + Level = 0x5, + Level2 = 0x6, + Comment = 0x7, + Comment2 = 0x8, + Comment3 = 0x9, + Song = 0xc, + Score = 0xd, + MapPack = 0xe, + CustomSong = 0xf, + Comment4 = 0x10, + User2 = 0x11, + Request = 0x12, + Message = 0x13, + LevelScore = 0x14, + Artist = 0x15, + SmartTemplate = 0x16, + SFX = 0x17, + SFX2 = 0x18, + CustomMusic = 0x19, + Options = 0x1a, + LevelList = 0x1b, + Level3 = 0x1c, + LevelList2 = 0x1d, + LevelList3 = 0x1e, + Level4 = 0x1f, + LocalLevelScore = 0x21, + URL = 0x22, +}; + +enum class CurrencySpriteType { + Orb = 1, + Star = 2, + Diamond = 3, + FireShard = 4, + IceShard = 5, + PoisonShard = 6, + ShadowShard = 7, + LavaShard = 8, + DemonKey = 9, + EarthShard = 10, + BloodShard = 11, + MetalShard = 12, + LightShard = 13, + SoulShard = 14, + Moon = 15 +}; + +enum class CurrencyRewardType { + // todo +}; + +enum class MenuAnimationType { + Scale = 0, + Move = 1, +}; + +enum class ShopType { + Normal, + Secret, + Community +}; + +enum class UpdateResponse { + Unknown, + UpToDate, + GameVerOutOfDate, + UpdateSuccess, +}; + +enum class UnlockType { + Cube = 0x1, + Col1 = 0x2, + Col2 = 0x3, + Ship = 0x4, + Ball = 0x5, + Bird = 0x6, + Dart = 0x7, + Robot = 0x8, + Spider = 0x9, + Streak = 0xA, + Death = 0xB, + GJItem = 0xC, + Swing = 0xD, + Jetpack = 0xE, + ShipFire = 0xF +}; + +enum class SpecialRewardItem { + FireShard = 0x1, + IceShard = 0x2, + PoisonShard = 0x3, + ShadowShard = 0x4, + LavaShard = 0x5, + BonusKey = 0x6, + Orbs = 0x7, + Diamonds = 0x8, + CustomItem = 0x9, + EarthShard = 0xA, + BloodShard = 0xB, + MetalShard = 0xC, + LightShard = 0xD, + SoulShard = 0xE +}; + +enum class EditCommand { + SmallLeft = 1, + SmallRight = 2, + SmallUp = 3, + SmallDown = 4, + + Left = 5, + Right = 6, + Up = 7, + Down = 8, + + BigLeft = 9, + BigRight = 10, + BigUp = 11, + BigDown = 12, + + TinyLeft = 13, + TinyRight = 14, + TinyUp = 15, + TinyDown = 16, + + HalfLeft = 17, + HalfRight = 18, + HalfUp = 19, + HalfDown = 20, + + FlipX = 21, + FlipY = 22, + RotateCW = 23, + RotateCCW = 24, + RotateCW45 = 25, + RotateCCW45 = 26, + RotateFree = 27, + RotateSnap = 28, + + Scale = 29, + ScaleXY = 30, + Skew = 31 +}; + +enum class SelectArtType { + Background = 0, + Ground = 1, +}; + +enum class UndoCommand { + Delete = 1, + New = 2, + Paste = 3, + DeleteMulti = 4, + Transform = 5, + Select = 6, +}; + +enum class EasingType { + None = 0, + EaseInOut = 1, + EaseIn = 2, + EaseOut = 3, + ElasticInOut = 4, + ElasticIn = 5, + ElasticOut = 6, + BounceInOut = 7, + BounceIn = 8, + BounceOut = 9, + ExponentialInOut = 10, + ExponentialIn = 11, + ExponentialOut = 12, + SineInOut = 13, + SineIn = 14, + SineOut = 15, + BackInOut = 16, + BackIn = 17, + BackOut = 18, +}; + +enum class GJDifficulty { + Auto = 0, + Easy = 1, + Normal = 2, + Hard = 3, + Harder = 4, + Insane = 5, + Demon = 6, + DemonEasy = 7, + DemonMedium = 8, + DemonInsane = 9, + DemonExtreme = 10 +}; + +enum class GJLevelType { + Local = 1, + Editor = 2, + Saved = 3 +}; + +enum class GJRewardType +{ + Unknown = 0x0, + Small = 0x1, + Large = 0x2, + SmallTreasure = 0x3, + LargeTreasure = 0x4, + Key10Treasure = 0x5, + Key25Treasure = 0x6, + Key50Treasure = 0x7, + Key100Treasure = 0x8 +}; + +enum class IconType { + Cube = 0, + Ship = 1, + Ball = 2, + Ufo = 3, + Wave = 4, + Robot = 5, + Spider = 6, + Swing = 7, + Jetpack = 8, + DeathEffect = 98, + Special = 99, + ShipFire = 101, +}; + +enum class GJChallengeType { + Unknown = 0, + Orbs = 1, + UserCoins = 2, + Stars = 3, + Moons = 4, +}; + +enum class GJScoreType { + Unknown = 0, + Creator = 1 +}; + +enum class LevelLeaderboardType { + Friends = 0, + Global = 1, + Weekly = 2 +}; + +enum class GJHttpType { + +}; + +enum class DialogChatPlacement { + Center = 0, + Top = 1, + Bottom = 2, +}; + +enum class DialogAnimationType { + Instant = 0, + FromCenter = 1, + FromLeft = 2, + FromRight = 3, + FromTop = 4, + // a 5th type is defined which acts exactly the same as FromTop +}; + + +// Geode Additions + +enum class ZLayer { + B5 = -5, + B4 = -3, + B3 = -1, + B2 = 1, + B1 = 3, + Default = 0, + T1 = 5, + T2 = 7, + T3 = 9, + T4 = 11, +}; + +enum class PlaybackMode { + Not = 0, + Playing = 1, + Paused = 2, +}; + +enum class ComparisonType { + Equals = 0, + Larger = 1, + Smaller = 2, +}; + +enum class MoveTargetType { + Both = 0, + XOnly = 1, + YOnly = 2, +}; + +enum class TouchToggleMode { + Normal = 0, + ToggleOn = 1, + ToggleOff = 2, +}; + +enum class LeaderboardState { + Default = 0, + Top100 = 1, + Global = 2, + Creator = 3, + Friends = 4, +}; + +// Wylie Addition (https://github.com/Wyliemaster/GD-Decompiled/blob/main/GD/code/headers/Layers/LevelSettingsLayer.h) +enum class Speed { + Normal = 0, + Slow = 1, + Fast = 2, + Faster = 3, + Fastest = 4, +}; diff --git a/broma_ida/types/fmod.hpp b/broma_ida/types/fmod.hpp new file mode 100644 index 0000000..2c1243e --- /dev/null +++ b/broma_ida/types/fmod.hpp @@ -0,0 +1,1359 @@ +/* ======================================================================================== */ +/* FMOD Core API - C++ header file. */ +/* Copyright (c), Firelight Technologies Pty, Ltd. 2004-2020. */ +/* */ +/* Use this header in conjunction with fmod_common.h (which contains all the constants / */ +/* callbacks) to develop using the C++ language. */ +/* */ +/* For more detail visit: */ +/* https://fmod.com/resources/documentation-api?version=2.0&page=core-api.html */ +/* */ +/* Modified by SpaghettDev */ +/* ======================================================================================== */ + +// TODO: add the other structs, instead of just keeping them as a typedef + +#define F_API __stdcall +#define F_CALL F_API +#define F_CALLBACK F_CALL + +// enums +typedef enum FMOD_RESULT +{ + FMOD_OK, + FMOD_ERR_BADCOMMAND, + FMOD_ERR_CHANNEL_ALLOC, + FMOD_ERR_CHANNEL_STOLEN, + FMOD_ERR_DMA, + FMOD_ERR_DSP_CONNECTION, + FMOD_ERR_DSP_DONTPROCESS, + FMOD_ERR_DSP_FORMAT, + FMOD_ERR_DSP_INUSE, + FMOD_ERR_DSP_NOTFOUND, + FMOD_ERR_DSP_RESERVED, + FMOD_ERR_DSP_SILENCE, + FMOD_ERR_DSP_TYPE, + FMOD_ERR_FILE_BAD, + FMOD_ERR_FILE_COULDNOTSEEK, + FMOD_ERR_FILE_DISKEJECTED, + FMOD_ERR_FILE_EOF, + FMOD_ERR_FILE_ENDOFDATA, + FMOD_ERR_FILE_NOTFOUND, + FMOD_ERR_FORMAT, + FMOD_ERR_HEADER_MISMATCH, + FMOD_ERR_HTTP, + FMOD_ERR_HTTP_ACCESS, + FMOD_ERR_HTTP_PROXY_AUTH, + FMOD_ERR_HTTP_SERVER_ERROR, + FMOD_ERR_HTTP_TIMEOUT, + FMOD_ERR_INITIALIZATION, + FMOD_ERR_INITIALIZED, + FMOD_ERR_INTERNAL, + FMOD_ERR_INVALID_FLOAT, + FMOD_ERR_INVALID_HANDLE, + FMOD_ERR_INVALID_PARAM, + FMOD_ERR_INVALID_POSITION, + FMOD_ERR_INVALID_SPEAKER, + FMOD_ERR_INVALID_SYNCPOINT, + FMOD_ERR_INVALID_THREAD, + FMOD_ERR_INVALID_VECTOR, + FMOD_ERR_MAXAUDIBLE, + FMOD_ERR_MEMORY, + FMOD_ERR_MEMORY_CANTPOINT, + FMOD_ERR_NEEDS3D, + FMOD_ERR_NEEDSHARDWARE, + FMOD_ERR_NET_CONNECT, + FMOD_ERR_NET_SOCKET_ERROR, + FMOD_ERR_NET_URL, + FMOD_ERR_NET_WOULD_BLOCK, + FMOD_ERR_NOTREADY, + FMOD_ERR_OUTPUT_ALLOCATED, + FMOD_ERR_OUTPUT_CREATEBUFFER, + FMOD_ERR_OUTPUT_DRIVERCALL, + FMOD_ERR_OUTPUT_FORMAT, + FMOD_ERR_OUTPUT_INIT, + FMOD_ERR_OUTPUT_NODRIVERS, + FMOD_ERR_PLUGIN, + FMOD_ERR_PLUGIN_MISSING, + FMOD_ERR_PLUGIN_RESOURCE, + FMOD_ERR_PLUGIN_VERSION, + FMOD_ERR_RECORD, + FMOD_ERR_REVERB_CHANNELGROUP, + FMOD_ERR_REVERB_INSTANCE, + FMOD_ERR_SUBSOUNDS, + FMOD_ERR_SUBSOUND_ALLOCATED, + FMOD_ERR_SUBSOUND_CANTMOVE, + FMOD_ERR_TAGNOTFOUND, + FMOD_ERR_TOOMANYCHANNELS, + FMOD_ERR_TRUNCATED, + FMOD_ERR_UNIMPLEMENTED, + FMOD_ERR_UNINITIALIZED, + FMOD_ERR_UNSUPPORTED, + FMOD_ERR_VERSION, + FMOD_ERR_EVENT_ALREADY_LOADED, + FMOD_ERR_EVENT_LIVEUPDATE_BUSY, + FMOD_ERR_EVENT_LIVEUPDATE_MISMATCH, + FMOD_ERR_EVENT_LIVEUPDATE_TIMEOUT, + FMOD_ERR_EVENT_NOTFOUND, + FMOD_ERR_STUDIO_UNINITIALIZED, + FMOD_ERR_STUDIO_NOT_LOADED, + FMOD_ERR_INVALID_STRING, + FMOD_ERR_ALREADY_LOCKED, + FMOD_ERR_NOT_LOCKED, + FMOD_ERR_RECORD_DISCONNECTED, + FMOD_ERR_TOOMANYSAMPLES, + + FMOD_RESULT_FORCEINT = 65536 +} FMOD_RESULT; + +typedef enum FMOD_OUTPUTTYPE +{ + FMOD_OUTPUTTYPE_AUTODETECT, + FMOD_OUTPUTTYPE_UNKNOWN, + FMOD_OUTPUTTYPE_NOSOUND, + FMOD_OUTPUTTYPE_WAVWRITER, + FMOD_OUTPUTTYPE_NOSOUND_NRT, + FMOD_OUTPUTTYPE_WAVWRITER_NRT, + FMOD_OUTPUTTYPE_WASAPI, + FMOD_OUTPUTTYPE_ASIO, + FMOD_OUTPUTTYPE_PULSEAUDIO, + FMOD_OUTPUTTYPE_ALSA, + FMOD_OUTPUTTYPE_COREAUDIO, + FMOD_OUTPUTTYPE_AUDIOTRACK, + FMOD_OUTPUTTYPE_OPENSL, + FMOD_OUTPUTTYPE_AUDIOOUT, + FMOD_OUTPUTTYPE_AUDIO3D, + FMOD_OUTPUTTYPE_WEBAUDIO, + FMOD_OUTPUTTYPE_NNAUDIO, + FMOD_OUTPUTTYPE_WINSONIC, + FMOD_OUTPUTTYPE_AAUDIO, + + FMOD_OUTPUTTYPE_MAX, + FMOD_OUTPUTTYPE_FORCEINT = 65536 +} FMOD_OUTPUTTYPE; + +typedef enum FMOD_SPEAKERMODE +{ + FMOD_SPEAKERMODE_DEFAULT, + FMOD_SPEAKERMODE_RAW, + FMOD_SPEAKERMODE_MONO, + FMOD_SPEAKERMODE_STEREO, + FMOD_SPEAKERMODE_QUAD, + FMOD_SPEAKERMODE_SURROUND, + FMOD_SPEAKERMODE_5POINT1, + FMOD_SPEAKERMODE_7POINT1, + FMOD_SPEAKERMODE_7POINT1POINT4, + + FMOD_SPEAKERMODE_MAX, + FMOD_SPEAKERMODE_FORCEINT = 65536 +} FMOD_SPEAKERMODE; + +typedef enum FMOD_CHANNELCONTROL_TYPE +{ + FMOD_CHANNELCONTROL_CHANNEL, + FMOD_CHANNELCONTROL_CHANNELGROUP, + + FMOD_CHANNELCONTROL_MAX, + FMOD_CHANNELCONTROL_FORCEINT = 65536 +} FMOD_CHANNELCONTROL_TYPE; + +typedef enum FMOD_CHANNELCONTROL_CALLBACK_TYPE +{ + FMOD_CHANNELCONTROL_CALLBACK_END, + FMOD_CHANNELCONTROL_CALLBACK_VIRTUALVOICE, + FMOD_CHANNELCONTROL_CALLBACK_SYNCPOINT, + FMOD_CHANNELCONTROL_CALLBACK_OCCLUSION, + + FMOD_CHANNELCONTROL_CALLBACK_MAX, + FMOD_CHANNELCONTROL_CALLBACK_FORCEINT = 65536 +} FMOD_CHANNELCONTROL_CALLBACK_TYPE; + +typedef enum FMOD_SPEAKER +{ + FMOD_SPEAKER_NONE = -1, + FMOD_SPEAKER_FRONT_LEFT = 0, + FMOD_SPEAKER_FRONT_RIGHT, + FMOD_SPEAKER_FRONT_CENTER, + FMOD_SPEAKER_LOW_FREQUENCY, + FMOD_SPEAKER_SURROUND_LEFT, + FMOD_SPEAKER_SURROUND_RIGHT, + FMOD_SPEAKER_BACK_LEFT, + FMOD_SPEAKER_BACK_RIGHT, + FMOD_SPEAKER_TOP_FRONT_LEFT, + FMOD_SPEAKER_TOP_FRONT_RIGHT, + FMOD_SPEAKER_TOP_BACK_LEFT, + FMOD_SPEAKER_TOP_BACK_RIGHT, + + FMOD_SPEAKER_MAX, + FMOD_SPEAKER_FORCEINT = 65536 +} FMOD_SPEAKER; + +typedef enum FMOD_DSP_RESAMPLER +{ + FMOD_DSP_RESAMPLER_DEFAULT, + FMOD_DSP_RESAMPLER_NOINTERP, + FMOD_DSP_RESAMPLER_LINEAR, + FMOD_DSP_RESAMPLER_CUBIC, + FMOD_DSP_RESAMPLER_SPLINE, + + FMOD_DSP_RESAMPLER_MAX, + FMOD_DSP_RESAMPLER_FORCEINT = 65536 +} FMOD_DSP_RESAMPLER; + +typedef enum FMOD_PLUGINTYPE +{ + FMOD_PLUGINTYPE_OUTPUT, + FMOD_PLUGINTYPE_CODEC, + FMOD_PLUGINTYPE_DSP, + + FMOD_PLUGINTYPE_MAX, + FMOD_PLUGINTYPE_FORCEINT = 65536 +} FMOD_PLUGINTYPE; + +typedef enum FMOD_DSPCONNECTION_TYPE +{ + FMOD_DSPCONNECTION_TYPE_STANDARD, + FMOD_DSPCONNECTION_TYPE_SIDECHAIN, + FMOD_DSPCONNECTION_TYPE_SEND, + FMOD_DSPCONNECTION_TYPE_SEND_SIDECHAIN, + + FMOD_DSPCONNECTION_TYPE_MAX, + FMOD_DSPCONNECTION_TYPE_FORCEINT = 65536 +} FMOD_DSPCONNECTION_TYPE; + +typedef enum +{ + FMOD_DSP_PARAMETER_TYPE_FLOAT, + FMOD_DSP_PARAMETER_TYPE_INT, + FMOD_DSP_PARAMETER_TYPE_BOOL, + FMOD_DSP_PARAMETER_TYPE_DATA, + + FMOD_DSP_PARAMETER_TYPE_MAX, + FMOD_DSP_PARAMETER_TYPE_FORCEINT = 65536 +} FMOD_DSP_PARAMETER_TYPE; + +typedef enum +{ + FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_LINEAR, + FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_AUTO, + FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_PIECEWISE_LINEAR, + + FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE_FORCEINT = 65536 +} FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE; + +typedef enum +{ + FMOD_DSP_TYPE_UNKNOWN, + FMOD_DSP_TYPE_MIXER, + FMOD_DSP_TYPE_OSCILLATOR, + FMOD_DSP_TYPE_LOWPASS, + FMOD_DSP_TYPE_ITLOWPASS, + FMOD_DSP_TYPE_HIGHPASS, + FMOD_DSP_TYPE_ECHO, + FMOD_DSP_TYPE_FADER, + FMOD_DSP_TYPE_FLANGE, + FMOD_DSP_TYPE_DISTORTION, + FMOD_DSP_TYPE_NORMALIZE, + FMOD_DSP_TYPE_LIMITER, + FMOD_DSP_TYPE_PARAMEQ, + FMOD_DSP_TYPE_PITCHSHIFT, + FMOD_DSP_TYPE_CHORUS, + FMOD_DSP_TYPE_VSTPLUGIN, + FMOD_DSP_TYPE_WINAMPPLUGIN, + FMOD_DSP_TYPE_ITECHO, + FMOD_DSP_TYPE_COMPRESSOR, + FMOD_DSP_TYPE_SFXREVERB, + FMOD_DSP_TYPE_LOWPASS_SIMPLE, + FMOD_DSP_TYPE_DELAY, + FMOD_DSP_TYPE_TREMOLO, + FMOD_DSP_TYPE_LADSPAPLUGIN, + FMOD_DSP_TYPE_SEND, + FMOD_DSP_TYPE_RETURN, + FMOD_DSP_TYPE_HIGHPASS_SIMPLE, + FMOD_DSP_TYPE_PAN, + FMOD_DSP_TYPE_THREE_EQ, + FMOD_DSP_TYPE_FFT, + FMOD_DSP_TYPE_LOUDNESS_METER, + FMOD_DSP_TYPE_ENVELOPEFOLLOWER, + FMOD_DSP_TYPE_CONVOLUTIONREVERB, + FMOD_DSP_TYPE_CHANNELMIX, + FMOD_DSP_TYPE_TRANSCEIVER, + FMOD_DSP_TYPE_OBJECTPAN, + FMOD_DSP_TYPE_MULTIBAND_EQ, + + FMOD_DSP_TYPE_MAX, + FMOD_DSP_TYPE_FORCEINT = 65536 /* Makes sure this enum is signed 32bit. */ +} FMOD_DSP_TYPE; + +typedef enum +{ + FMOD_DSP_PROCESS_PERFORM, + FMOD_DSP_PROCESS_QUERY +} FMOD_DSP_PROCESS_OPERATION; + +typedef enum FMOD_TAGTYPE +{ + FMOD_TAGTYPE_UNKNOWN, + FMOD_TAGTYPE_ID3V1, + FMOD_TAGTYPE_ID3V2, + FMOD_TAGTYPE_VORBISCOMMENT, + FMOD_TAGTYPE_SHOUTCAST, + FMOD_TAGTYPE_ICECAST, + FMOD_TAGTYPE_ASF, + FMOD_TAGTYPE_MIDI, + FMOD_TAGTYPE_PLAYLIST, + FMOD_TAGTYPE_FMOD, + FMOD_TAGTYPE_USER, + + FMOD_TAGTYPE_MAX, + FMOD_TAGTYPE_FORCEINT = 65536 +} FMOD_TAGTYPE; + +typedef enum FMOD_TAGDATATYPE +{ + FMOD_TAGDATATYPE_BINARY, + FMOD_TAGDATATYPE_INT, + FMOD_TAGDATATYPE_FLOAT, + FMOD_TAGDATATYPE_STRING, + FMOD_TAGDATATYPE_STRING_UTF16, + FMOD_TAGDATATYPE_STRING_UTF16BE, + FMOD_TAGDATATYPE_STRING_UTF8, + + FMOD_TAGDATATYPE_MAX, + FMOD_TAGDATATYPE_FORCEINT = 65536 +} FMOD_TAGDATATYPE; + +typedef enum FMOD_SOUND_FORMAT +{ + FMOD_SOUND_FORMAT_NONE, + FMOD_SOUND_FORMAT_PCM8, + FMOD_SOUND_FORMAT_PCM16, + FMOD_SOUND_FORMAT_PCM24, + FMOD_SOUND_FORMAT_PCM32, + FMOD_SOUND_FORMAT_PCMFLOAT, + FMOD_SOUND_FORMAT_BITSTREAM, + + FMOD_SOUND_FORMAT_MAX, + FMOD_SOUND_FORMAT_FORCEINT = 65536 +} FMOD_SOUND_FORMAT; + +typedef enum FMOD_CHANNELORDER +{ + FMOD_CHANNELORDER_DEFAULT, + FMOD_CHANNELORDER_WAVEFORMAT, + FMOD_CHANNELORDER_PROTOOLS, + FMOD_CHANNELORDER_ALLMONO, + FMOD_CHANNELORDER_ALLSTEREO, + FMOD_CHANNELORDER_ALSA, + + FMOD_CHANNELORDER_MAX, + FMOD_CHANNELORDER_FORCEINT = 65536 +} FMOD_CHANNELORDER; + +typedef enum FMOD_SOUND_TYPE +{ + FMOD_SOUND_TYPE_UNKNOWN, + FMOD_SOUND_TYPE_AIFF, + FMOD_SOUND_TYPE_ASF, + FMOD_SOUND_TYPE_DLS, + FMOD_SOUND_TYPE_FLAC, + FMOD_SOUND_TYPE_FSB, + FMOD_SOUND_TYPE_IT, + FMOD_SOUND_TYPE_MIDI, + FMOD_SOUND_TYPE_MOD, + FMOD_SOUND_TYPE_MPEG, + FMOD_SOUND_TYPE_OGGVORBIS, + FMOD_SOUND_TYPE_PLAYLIST, + FMOD_SOUND_TYPE_RAW, + FMOD_SOUND_TYPE_S3M, + FMOD_SOUND_TYPE_USER, + FMOD_SOUND_TYPE_WAV, + FMOD_SOUND_TYPE_XM, + FMOD_SOUND_TYPE_XMA, + FMOD_SOUND_TYPE_AUDIOQUEUE, + FMOD_SOUND_TYPE_AT9, + FMOD_SOUND_TYPE_VORBIS, + FMOD_SOUND_TYPE_MEDIA_FOUNDATION, + FMOD_SOUND_TYPE_MEDIACODEC, + FMOD_SOUND_TYPE_FADPCM, + FMOD_SOUND_TYPE_OPUS, + + FMOD_SOUND_TYPE_MAX, + FMOD_SOUND_TYPE_FORCEINT = 65536 +} FMOD_SOUND_TYPE; + +typedef enum FMOD_OPENSTATE +{ + FMOD_OPENSTATE_READY, + FMOD_OPENSTATE_LOADING, + FMOD_OPENSTATE_ERROR, + FMOD_OPENSTATE_CONNECTING, + FMOD_OPENSTATE_BUFFERING, + FMOD_OPENSTATE_SEEKING, + FMOD_OPENSTATE_PLAYING, + FMOD_OPENSTATE_SETPOSITION, + + FMOD_OPENSTATE_MAX, + FMOD_OPENSTATE_FORCEINT = 65536 +} FMOD_OPENSTATE; + +typedef enum FMOD_SOUNDGROUP_BEHAVIOR +{ + FMOD_SOUNDGROUP_BEHAVIOR_FAIL, + FMOD_SOUNDGROUP_BEHAVIOR_MUTE, + FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST, + + FMOD_SOUNDGROUP_BEHAVIOR_MAX, + FMOD_SOUNDGROUP_BEHAVIOR_FORCEINT = 65536 +} FMOD_SOUNDGROUP_BEHAVIOR; + + +// typedefs +/* + FMOD core types +*/ +typedef int FMOD_BOOL; +typedef struct FMOD_SYSTEM FMOD_SYSTEM; +typedef struct FMOD_SOUND FMOD_SOUND; +typedef struct FMOD_CHANNELCONTROL FMOD_CHANNELCONTROL; +typedef struct FMOD_CHANNEL FMOD_CHANNEL; +typedef struct FMOD_CHANNELGROUP FMOD_CHANNELGROUP; +typedef struct FMOD_SOUNDGROUP FMOD_SOUNDGROUP; +typedef struct FMOD_REVERB3D FMOD_REVERB3D; +typedef struct FMOD_DSP FMOD_DSP; +typedef struct FMOD_DSPCONNECTION FMOD_DSPCONNECTION; +typedef struct FMOD_POLYGON FMOD_POLYGON; +typedef struct FMOD_GEOMETRY FMOD_GEOMETRY; +typedef struct FMOD_SYNCPOINT FMOD_SYNCPOINT; +typedef struct FMOD_ASYNCREADINFO FMOD_ASYNCREADINFO; +typedef unsigned int FMOD_PORT_TYPE; +typedef unsigned long long FMOD_PORT_INDEX; + +typedef unsigned int FMOD_TIMEUNIT; +typedef unsigned int FMOD_DEBUG_FLAGS; +typedef unsigned int FMOD_CHANNELMASK; + +typedef unsigned int FMOD_SYSTEM_CALLBACK_TYPE; +typedef unsigned int FMOD_MEMORY_TYPE; + +typedef FMOD_RESULT (F_CALL *FMOD_DEBUG_CALLBACK) (FMOD_DEBUG_FLAGS flags, const char *file, int line, const char* func, const char* message); +typedef FMOD_RESULT (F_CALL *FMOD_SYSTEM_CALLBACK) (FMOD_SYSTEM *system, FMOD_SYSTEM_CALLBACK_TYPE type, void *commanddata1, void* commanddata2, void *userdata); +typedef FMOD_RESULT (F_CALL *FMOD_CHANNELCONTROL_CALLBACK) (FMOD_CHANNELCONTROL *channelcontrol, FMOD_CHANNELCONTROL_TYPE controltype, FMOD_CHANNELCONTROL_CALLBACK_TYPE callbacktype, void *commanddata1, void *commanddata2); +typedef FMOD_RESULT (F_CALL *FMOD_SOUND_NONBLOCK_CALLBACK) (FMOD_SOUND *sound, FMOD_RESULT result); +typedef FMOD_RESULT (F_CALL *FMOD_SOUND_PCMREAD_CALLBACK) (FMOD_SOUND *sound, void *data, unsigned int datalen); +typedef FMOD_RESULT (F_CALL *FMOD_SOUND_PCMSETPOS_CALLBACK) (FMOD_SOUND *sound, int subsound, unsigned int position, FMOD_TIMEUNIT postype); +typedef FMOD_RESULT (F_CALL *FMOD_FILE_OPEN_CALLBACK) (const char *name, unsigned int *filesize, void **handle, void *userdata); +typedef FMOD_RESULT (F_CALL *FMOD_FILE_CLOSE_CALLBACK) (void *handle, void *userdata); +typedef FMOD_RESULT (F_CALL *FMOD_FILE_READ_CALLBACK) (void *handle, void *buffer, unsigned int sizebytes, unsigned int *bytesread, void *userdata); +typedef FMOD_RESULT (F_CALL *FMOD_FILE_SEEK_CALLBACK) (void *handle, unsigned int pos, void *userdata); +typedef FMOD_RESULT (F_CALL *FMOD_FILE_ASYNCREAD_CALLBACK) (FMOD_ASYNCREADINFO *info, void *userdata); +typedef FMOD_RESULT (F_CALL *FMOD_FILE_ASYNCCANCEL_CALLBACK)(FMOD_ASYNCREADINFO *info, void *userdata); +typedef void (F_CALL *FMOD_FILE_ASYNCDONE_FUNC) (FMOD_ASYNCREADINFO *info, FMOD_RESULT result); +typedef void* (F_CALL *FMOD_MEMORY_ALLOC_CALLBACK) (unsigned int size, FMOD_MEMORY_TYPE type, const char *sourcestr); +typedef void* (F_CALL *FMOD_MEMORY_REALLOC_CALLBACK) (void *ptr, unsigned int size, FMOD_MEMORY_TYPE type, const char *sourcestr); +typedef void (F_CALL *FMOD_MEMORY_FREE_CALLBACK) (void *ptr, FMOD_MEMORY_TYPE type, const char *sourcestr); +typedef float (F_CALL *FMOD_3D_ROLLOFF_CALLBACK) (FMOD_CHANNELCONTROL *channelcontrol, float distance); + +/* + DSP Callbacks +*/ +typedef struct FMOD_DSP_STATE FMOD_DSP_STATE; +typedef struct FMOD_DSP_BUFFER_ARRAY FMOD_DSP_BUFFER_ARRAY; +typedef FMOD_RESULT (F_CALL *FMOD_DSP_CREATE_CALLBACK) (FMOD_DSP_STATE *dsp_state); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_RELEASE_CALLBACK) (FMOD_DSP_STATE *dsp_state); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_RESET_CALLBACK) (FMOD_DSP_STATE *dsp_state); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_READ_CALLBACK) (FMOD_DSP_STATE *dsp_state, float *inbuffer, float *outbuffer, unsigned int length, int inchannels, int *outchannels); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_PROCESS_CALLBACK) (FMOD_DSP_STATE *dsp_state, unsigned int length, const FMOD_DSP_BUFFER_ARRAY *inbufferarray, FMOD_DSP_BUFFER_ARRAY *outbufferarray, FMOD_BOOL inputsidle, FMOD_DSP_PROCESS_OPERATION op); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SETPOSITION_CALLBACK) (FMOD_DSP_STATE *dsp_state, unsigned int pos); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SHOULDIPROCESS_CALLBACK) (FMOD_DSP_STATE *dsp_state, FMOD_BOOL inputsidle, unsigned int length, FMOD_CHANNELMASK inmask, int inchannels, FMOD_SPEAKERMODE speakermode); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SETPARAM_FLOAT_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, float value); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SETPARAM_INT_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, int value); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SETPARAM_BOOL_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, FMOD_BOOL value); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SETPARAM_DATA_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, void *data, unsigned int length); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_GETPARAM_FLOAT_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, float *value, char *valuestr); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_GETPARAM_INT_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, int *value, char *valuestr); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_GETPARAM_BOOL_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, FMOD_BOOL *value, char *valuestr); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_GETPARAM_DATA_CALLBACK) (FMOD_DSP_STATE *dsp_state, int index, void **data, unsigned int *length, char *valuestr); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SYSTEM_REGISTER_CALLBACK) (FMOD_DSP_STATE *dsp_state); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SYSTEM_DEREGISTER_CALLBACK) (FMOD_DSP_STATE *dsp_state); +typedef FMOD_RESULT (F_CALL *FMOD_DSP_SYSTEM_MIX_CALLBACK) (FMOD_DSP_STATE *dsp_state, int stage); + +/* + Codec callbacks +*/ +struct FMOD_CODEC_STATE; +struct FMOD_CODEC_WAVEFORMAT; +struct FMOD_CREATESOUNDEXINFO; +typedef unsigned int FMOD_MODE; +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_OPEN_CALLBACK) (FMOD_CODEC_STATE *codec_state, FMOD_MODE usermode, FMOD_CREATESOUNDEXINFO *userexinfo); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_CLOSE_CALLBACK) (FMOD_CODEC_STATE *codec_state); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_READ_CALLBACK) (FMOD_CODEC_STATE *codec_state, void *buffer, unsigned int samples_in, unsigned int *samples_out); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_GETLENGTH_CALLBACK) (FMOD_CODEC_STATE *codec_state, unsigned int *length, FMOD_TIMEUNIT lengthtype); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_SETPOSITION_CALLBACK) (FMOD_CODEC_STATE *codec_state, int subsound, unsigned int position, FMOD_TIMEUNIT postype); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_GETPOSITION_CALLBACK) (FMOD_CODEC_STATE *codec_state, unsigned int *position, FMOD_TIMEUNIT postype); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_SOUNDCREATE_CALLBACK) (FMOD_CODEC_STATE *codec_state, int subsound, FMOD_SOUND *sound); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_METADATA_CALLBACK) (FMOD_CODEC_STATE *codec_state, FMOD_TAGTYPE tagtype, char *name, void *data, unsigned int datalen, FMOD_TAGDATATYPE datatype, int unique); +typedef FMOD_RESULT (F_CALLBACK *FMOD_CODEC_GETWAVEFORMAT_CALLBACK)(FMOD_CODEC_STATE *codec_state, int index, FMOD_CODEC_WAVEFORMAT *waveformat); + +struct FMOD_CODEC_STATE +{ + int numsubsounds; + FMOD_CODEC_WAVEFORMAT *waveformat; + void *plugindata; + + void *filehandle; + unsigned int filesize; + FMOD_FILE_READ_CALLBACK fileread; + FMOD_FILE_SEEK_CALLBACK fileseek; + FMOD_CODEC_METADATA_CALLBACK metadata; + + int waveformatversion; +}; + +struct FMOD_CODEC_WAVEFORMAT +{ + const char* name; + FMOD_SOUND_FORMAT format; + int channels; + int frequency; + unsigned int lengthbytes; + unsigned int lengthpcm; + unsigned int pcmblocksize; + int loopstart; + int loopend; + FMOD_MODE mode; + FMOD_CHANNELMASK channelmask; + FMOD_CHANNELORDER channelorder; + float peakvolume; +}; + +typedef struct FMOD_GUID +{ + unsigned int Data1; + unsigned short Data2; + unsigned short Data3; + unsigned char Data4[8]; +} FMOD_GUID; + +typedef struct FMOD_CREATESOUNDEXINFO +{ + int cbsize; + unsigned int length; + unsigned int fileoffset; + int numchannels; + int defaultfrequency; + FMOD_SOUND_FORMAT format; + unsigned int decodebuffersize; + int initialsubsound; + int numsubsounds; + int *inclusionlist; + int inclusionlistnum; + FMOD_SOUND_PCMREAD_CALLBACK pcmreadcallback; + FMOD_SOUND_PCMSETPOS_CALLBACK pcmsetposcallback; + FMOD_SOUND_NONBLOCK_CALLBACK nonblockcallback; + const char *dlsname; + const char *encryptionkey; + int maxpolyphony; + void *userdata; + FMOD_SOUND_TYPE suggestedsoundtype; + FMOD_FILE_OPEN_CALLBACK fileuseropen; + FMOD_FILE_CLOSE_CALLBACK fileuserclose; + FMOD_FILE_READ_CALLBACK fileuserread; + FMOD_FILE_SEEK_CALLBACK fileuserseek; + FMOD_FILE_ASYNCREAD_CALLBACK fileuserasyncread; + FMOD_FILE_ASYNCCANCEL_CALLBACK fileuserasynccancel; + void *fileuserdata; + int filebuffersize; + FMOD_CHANNELORDER channelorder; + FMOD_SOUNDGROUP *initialsoundgroup; + unsigned int initialseekposition; + FMOD_TIMEUNIT initialseekpostype; + int ignoresetfilesystem; + unsigned int audioqueuepolicy; + unsigned int minmidigranularity; + int nonblockthreadid; + FMOD_GUID *fsbguid; +} FMOD_CREATESOUNDEXINFO; + +/* + Output callbacks +*/ +/* + Output functions +*/ +struct FMOD_OUTPUT_STATE; +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_READFROMMIXER_FUNC) (FMOD_OUTPUT_STATE *output_state, void *buffer, unsigned int length); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_COPYPORT_FUNC) (FMOD_OUTPUT_STATE *output_state, int portId, void *buffer, unsigned int length); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_REQUESTRESET_FUNC) (FMOD_OUTPUT_STATE *output_state); +typedef void * (F_CALL *FMOD_OUTPUT_ALLOC_FUNC) (unsigned int size, unsigned int align, const char *file, int line); +typedef void (F_CALL *FMOD_OUTPUT_FREE_FUNC) (void *ptr, const char *file, int line); +typedef void (F_CALL *FMOD_OUTPUT_LOG_FUNC) (FMOD_DEBUG_FLAGS level, const char *file, int line, const char *function, const char *string); + +struct FMOD_OUTPUT_STATE +{ + void *plugindata; + FMOD_OUTPUT_READFROMMIXER_FUNC readfrommixer; + FMOD_OUTPUT_ALLOC_FUNC alloc; + FMOD_OUTPUT_FREE_FUNC free; + FMOD_OUTPUT_LOG_FUNC log; + FMOD_OUTPUT_COPYPORT_FUNC copyport; + FMOD_OUTPUT_REQUESTRESET_FUNC requestreset; +}; + +struct FMOD_OUTPUT_OBJECT3DINFO; +typedef unsigned int FMOD_INITFLAGS; +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_GETNUMDRIVERS_CALLBACK) (FMOD_OUTPUT_STATE *output_state, int *numdrivers); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_GETDRIVERINFO_CALLBACK) (FMOD_OUTPUT_STATE *output_state, int id, char *name, int namelen, FMOD_GUID *guid, int *systemrate, FMOD_SPEAKERMODE *speakermode, int *speakermodechannels); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_INIT_CALLBACK) (FMOD_OUTPUT_STATE *output_state, int selecteddriver, FMOD_INITFLAGS flags, int *outputrate, FMOD_SPEAKERMODE *speakermode, int *speakermodechannels, FMOD_SOUND_FORMAT *outputformat, int dspbufferlength, int dspnumbuffers, void *extradriverdata); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_START_CALLBACK) (FMOD_OUTPUT_STATE *output_state); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_STOP_CALLBACK) (FMOD_OUTPUT_STATE *output_state); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_CLOSE_CALLBACK) (FMOD_OUTPUT_STATE *output_state); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_UPDATE_CALLBACK) (FMOD_OUTPUT_STATE *output_state); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_GETHANDLE_CALLBACK) (FMOD_OUTPUT_STATE *output_state, void **handle); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_GETPOSITION_CALLBACK) (FMOD_OUTPUT_STATE *output_state, unsigned int *pcm); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_LOCK_CALLBACK) (FMOD_OUTPUT_STATE *output_state, unsigned int offset, unsigned int length, void **ptr1, void **ptr2, unsigned int *len1, unsigned int *len2); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_UNLOCK_CALLBACK) (FMOD_OUTPUT_STATE *output_state, void *ptr1, void *ptr2, unsigned int len1, unsigned int len2); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_MIXER_CALLBACK) (FMOD_OUTPUT_STATE *output_state); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_OBJECT3DGETINFO_CALLBACK) (FMOD_OUTPUT_STATE *output_state, int *maxhardwareobjects); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_OBJECT3DALLOC_CALLBACK) (FMOD_OUTPUT_STATE *output_state, void **object3d); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_OBJECT3DFREE_CALLBACK) (FMOD_OUTPUT_STATE *output_state, void *object3d); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_OBJECT3DUPDATE_CALLBACK) (FMOD_OUTPUT_STATE *output_state, void *object3d, const FMOD_OUTPUT_OBJECT3DINFO *info); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_OPENPORT_CALLBACK) (FMOD_OUTPUT_STATE *output_state, FMOD_PORT_TYPE portType, FMOD_PORT_INDEX portIndex, int *portId, int *portRate, int *portChannels, FMOD_SOUND_FORMAT *portFormat); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_CLOSEPORT_CALLBACK) (FMOD_OUTPUT_STATE *output_state, int portId); +typedef FMOD_RESULT (F_CALL *FMOD_OUTPUT_DEVICELISTCHANGED_CALLBACK)(FMOD_OUTPUT_STATE *output_state); + +typedef struct FMOD_VECTOR +{ + float x; + float y; + float z; +} FMOD_VECTOR; + +struct FMOD_OUTPUT_OBJECT3DINFO +{ + float *buffer; + unsigned int bufferlength; + FMOD_VECTOR position; + float gain; + float spread; + float priority; +}; + +typedef unsigned int FMOD_DRIVER_STATE; + + +// structs +typedef struct FMOD_ADVANCEDSETTINGS +{ + int cbSize; + int maxMPEGCodecs; + int maxADPCMCodecs; + int maxXMACodecs; + int maxVorbisCodecs; + int maxAT9Codecs; + int maxFADPCMCodecs; + int maxPCMCodecs; + int ASIONumChannels; + char **ASIOChannelList; + FMOD_SPEAKER *ASIOSpeakerList; + float vol0virtualvol; + unsigned int defaultDecodeBufferSize; + unsigned short profilePort; + unsigned int geometryMaxFadeTime; + float distanceFilterCenterFreq; + int reverb3Dinstance; + int DSPBufferPoolSize; + unsigned int stackSizeStream; + unsigned int stackSizeNonBlocking; + unsigned int stackSizeMixer; + FMOD_DSP_RESAMPLER resamplerMethod; + unsigned int commandQueueSize; + unsigned int randomSeed; +} FMOD_ADVANCEDSETTINGS; + +typedef struct FMOD_PLUGINLIST +{ + FMOD_PLUGINTYPE type; + void *description; +} FMOD_PLUGINLIST; + +typedef struct FMOD_DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR +{ + int numpoints; + float *pointparamvalues; + float *pointpositions; +} FMOD_DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR; + +typedef struct FMOD_DSP_PARAMETER_FLOAT_MAPPING +{ + FMOD_DSP_PARAMETER_FLOAT_MAPPING_TYPE type; + FMOD_DSP_PARAMETER_FLOAT_MAPPING_PIECEWISE_LINEAR piecewiselinearmapping; +} FMOD_DSP_PARAMETER_FLOAT_MAPPING; + +typedef struct FMOD_DSP_PARAMETER_DESC_FLOAT +{ + float min; + float max; + float defaultval; + FMOD_DSP_PARAMETER_FLOAT_MAPPING mapping; +} FMOD_DSP_PARAMETER_DESC_FLOAT; + +typedef struct FMOD_DSP_PARAMETER_DESC_INT +{ + int min; + int max; + int defaultval; + FMOD_BOOL goestoinf; + const char* const* valuenames; +} FMOD_DSP_PARAMETER_DESC_INT; + +typedef struct FMOD_DSP_PARAMETER_DESC_BOOL +{ + FMOD_BOOL defaultval; + const char* const* valuenames; +} FMOD_DSP_PARAMETER_DESC_BOOL; + +typedef struct FMOD_DSP_PARAMETER_DESC_DATA +{ + int datatype; +} FMOD_DSP_PARAMETER_DESC_DATA; + +typedef struct FMOD_DSP_PARAMETER_DESC +{ + FMOD_DSP_PARAMETER_TYPE type; + char name[16]; + char label[16]; + const char *description; + + union + { + FMOD_DSP_PARAMETER_DESC_FLOAT floatdesc; + FMOD_DSP_PARAMETER_DESC_INT intdesc; + FMOD_DSP_PARAMETER_DESC_BOOL booldesc; + FMOD_DSP_PARAMETER_DESC_DATA datadesc; + }; +} FMOD_DSP_PARAMETER_DESC; + +typedef struct FMOD_DSP_METERING_INFO +{ + int numsamples; + float peaklevel[32]; + float rmslevel[32]; + short numchannels; +} FMOD_DSP_METERING_INFO; + +typedef struct FMOD_DSP_DESCRIPTION +{ + unsigned int pluginsdkversion; + char name[32]; + unsigned int version; + int numinputbuffers; + int numoutputbuffers; + FMOD_DSP_CREATE_CALLBACK create; + FMOD_DSP_RELEASE_CALLBACK release; + FMOD_DSP_RESET_CALLBACK reset; + FMOD_DSP_READ_CALLBACK read; + FMOD_DSP_PROCESS_CALLBACK process; + FMOD_DSP_SETPOSITION_CALLBACK setposition; + + int numparameters; + FMOD_DSP_PARAMETER_DESC **paramdesc; + FMOD_DSP_SETPARAM_FLOAT_CALLBACK setparameterfloat; + FMOD_DSP_SETPARAM_INT_CALLBACK setparameterint; + FMOD_DSP_SETPARAM_BOOL_CALLBACK setparameterbool; + FMOD_DSP_SETPARAM_DATA_CALLBACK setparameterdata; + FMOD_DSP_GETPARAM_FLOAT_CALLBACK getparameterfloat; + FMOD_DSP_GETPARAM_INT_CALLBACK getparameterint; + FMOD_DSP_GETPARAM_BOOL_CALLBACK getparameterbool; + FMOD_DSP_GETPARAM_DATA_CALLBACK getparameterdata; + FMOD_DSP_SHOULDIPROCESS_CALLBACK shouldiprocess; + void *userdata; + + FMOD_DSP_SYSTEM_REGISTER_CALLBACK sys_register; + FMOD_DSP_SYSTEM_DEREGISTER_CALLBACK sys_deregister; + FMOD_DSP_SYSTEM_MIX_CALLBACK sys_mix; + +} FMOD_DSP_DESCRIPTION; + +typedef struct FMOD_CODEC_DESCRIPTION +{ + const char *name; + unsigned int version; + int defaultasstream; + FMOD_TIMEUNIT timeunits; + FMOD_CODEC_OPEN_CALLBACK open; + FMOD_CODEC_CLOSE_CALLBACK close; + FMOD_CODEC_READ_CALLBACK read; + FMOD_CODEC_GETLENGTH_CALLBACK getlength; + FMOD_CODEC_SETPOSITION_CALLBACK setposition; + FMOD_CODEC_GETPOSITION_CALLBACK getposition; + FMOD_CODEC_SOUNDCREATE_CALLBACK soundcreate; + FMOD_CODEC_GETWAVEFORMAT_CALLBACK getwaveformat; +} FMOD_CODEC_DESCRIPTION; + +typedef unsigned int FMOD_OUTPUT_METHOD; +typedef struct FMOD_OUTPUT_DESCRIPTION +{ + unsigned int apiversion; + const char *name; + unsigned int version; + FMOD_OUTPUT_METHOD polling; /* This will become "method" on the next major version */ + FMOD_OUTPUT_GETNUMDRIVERS_CALLBACK getnumdrivers; + FMOD_OUTPUT_GETDRIVERINFO_CALLBACK getdriverinfo; + FMOD_OUTPUT_INIT_CALLBACK init; + FMOD_OUTPUT_START_CALLBACK start; + FMOD_OUTPUT_STOP_CALLBACK stop; + FMOD_OUTPUT_CLOSE_CALLBACK close; + FMOD_OUTPUT_UPDATE_CALLBACK update; + FMOD_OUTPUT_GETHANDLE_CALLBACK gethandle; + FMOD_OUTPUT_GETPOSITION_CALLBACK getposition; + FMOD_OUTPUT_LOCK_CALLBACK lock; + FMOD_OUTPUT_UNLOCK_CALLBACK unlock; + FMOD_OUTPUT_MIXER_CALLBACK mixer; + FMOD_OUTPUT_OBJECT3DGETINFO_CALLBACK object3dgetinfo; + FMOD_OUTPUT_OBJECT3DALLOC_CALLBACK object3dalloc; + FMOD_OUTPUT_OBJECT3DFREE_CALLBACK object3dfree; + FMOD_OUTPUT_OBJECT3DUPDATE_CALLBACK object3dupdate; + FMOD_OUTPUT_OPENPORT_CALLBACK openport; + FMOD_OUTPUT_CLOSEPORT_CALLBACK closeport; + FMOD_OUTPUT_DEVICELISTCHANGED_CALLBACK devicelistchanged; +} FMOD_OUTPUT_DESCRIPTION; + +typedef struct FMOD_TAG +{ + FMOD_TAGTYPE type; + FMOD_TAGDATATYPE datatype; + char *name; + void *data; + unsigned int datalen; + FMOD_BOOL updated; +} FMOD_TAG; + +typedef struct FMOD_REVERB_PROPERTIES +{ + float DecayTime; + float EarlyDelay; + float LateDelay; + float HFReference; + float HFDecayRatio; + float Diffusion; + float Density; + float LowShelfFrequency; + float LowShelfGain; + float HighCut; + float EarlyLateMix; + float WetLevel; +} FMOD_REVERB_PROPERTIES; + + +namespace FMOD +{ + // Channel + class System; + class DSP; + class Sound; + class ChannelGroup; + class Channel; + + class DSPConnection + { + private: + // Constructor made private so user cannot statically instance a DSPConnection class. Appropriate DSPConnection creation or retrieval function must be used. + DSPConnection(); + DSPConnection(const DSPConnection &); + + public: + FMOD_RESULT F_API getInput (DSP **input); + FMOD_RESULT F_API getOutput (DSP **output); + FMOD_RESULT F_API setMix (float volume); + FMOD_RESULT F_API getMix (float *volume); + FMOD_RESULT F_API setMixMatrix (float *matrix, int outchannels, int inchannels, int inchannel_hop = 0); + FMOD_RESULT F_API getMixMatrix (float *matrix, int *outchannels, int *inchannels, int inchannel_hop = 0); + FMOD_RESULT F_API getType (FMOD_DSPCONNECTION_TYPE *type); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + }; + + class DSP + { + private: + // Constructor made private so user cannot statically instance a DSP class. Appropriate DSP creation or retrieval function must be used. + DSP(); + DSP(const DSP &); + + public: + FMOD_RESULT F_API release (); + FMOD_RESULT F_API getSystemObject (System **system); + + // Connection / disconnection / input and output enumeration. + FMOD_RESULT F_API addInput (DSP *input, DSPConnection **connection = 0, FMOD_DSPCONNECTION_TYPE type = FMOD_DSPCONNECTION_TYPE_STANDARD); + FMOD_RESULT F_API disconnectFrom (DSP *target, DSPConnection *connection = 0); + FMOD_RESULT F_API disconnectAll (bool inputs, bool outputs); + FMOD_RESULT F_API getNumInputs (int *numinputs); + FMOD_RESULT F_API getNumOutputs (int *numoutputs); + FMOD_RESULT F_API getInput (int index, DSP **input, DSPConnection **inputconnection); + FMOD_RESULT F_API getOutput (int index, DSP **output, DSPConnection **outputconnection); + + // DSP unit control. + FMOD_RESULT F_API setActive (bool active); + FMOD_RESULT F_API getActive (bool *active); + FMOD_RESULT F_API setBypass (bool bypass); + FMOD_RESULT F_API getBypass (bool *bypass); + FMOD_RESULT F_API setWetDryMix (float prewet, float postwet, float dry); + FMOD_RESULT F_API getWetDryMix (float *prewet, float *postwet, float *dry); + FMOD_RESULT F_API setChannelFormat (FMOD_CHANNELMASK channelmask, int numchannels, FMOD_SPEAKERMODE source_speakermode); + FMOD_RESULT F_API getChannelFormat (FMOD_CHANNELMASK *channelmask, int *numchannels, FMOD_SPEAKERMODE *source_speakermode); + FMOD_RESULT F_API getOutputChannelFormat (FMOD_CHANNELMASK inmask, int inchannels, FMOD_SPEAKERMODE inspeakermode, FMOD_CHANNELMASK *outmask, int *outchannels, FMOD_SPEAKERMODE *outspeakermode); + FMOD_RESULT F_API reset (); + + // DSP parameter control. + FMOD_RESULT F_API setParameterFloat (int index, float value); + FMOD_RESULT F_API setParameterInt (int index, int value); + FMOD_RESULT F_API setParameterBool (int index, bool value); + FMOD_RESULT F_API setParameterData (int index, void *data, unsigned int length); + FMOD_RESULT F_API getParameterFloat (int index, float *value, char *valuestr, int valuestrlen); + FMOD_RESULT F_API getParameterInt (int index, int *value, char *valuestr, int valuestrlen); + FMOD_RESULT F_API getParameterBool (int index, bool *value, char *valuestr, int valuestrlen); + FMOD_RESULT F_API getParameterData (int index, void **data, unsigned int *length, char *valuestr, int valuestrlen); + FMOD_RESULT F_API getNumParameters (int *numparams); + FMOD_RESULT F_API getParameterInfo (int index, FMOD_DSP_PARAMETER_DESC **desc); + FMOD_RESULT F_API getDataParameterIndex (int datatype, int *index); + FMOD_RESULT F_API showConfigDialog (void *hwnd, bool show); + + // DSP attributes. + FMOD_RESULT F_API getInfo (char *name, unsigned int *version, int *channels, int *configwidth, int *configheight); + FMOD_RESULT F_API getType (FMOD_DSP_TYPE *type); + FMOD_RESULT F_API getIdle (bool *idle); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + + // Metering. + FMOD_RESULT F_API setMeteringEnabled (bool inputEnabled, bool outputEnabled); + FMOD_RESULT F_API getMeteringEnabled (bool *inputEnabled, bool *outputEnabled); + FMOD_RESULT F_API getMeteringInfo (FMOD_DSP_METERING_INFO *inputInfo, FMOD_DSP_METERING_INFO *outputInfo); + FMOD_RESULT F_API getCPUUsage (unsigned int *exclusive, unsigned int *inclusive); + }; + + class SoundGroup + { + private: + // Constructor made private so user cannot statically instance a SoundGroup class. Appropriate SoundGroup creation or retrieval function must be used. + SoundGroup(); + SoundGroup(const SoundGroup &); + + public: + FMOD_RESULT F_API release (); + FMOD_RESULT F_API getSystemObject (System **system); + + // SoundGroup control functions. + FMOD_RESULT F_API setMaxAudible (int maxaudible); + FMOD_RESULT F_API getMaxAudible (int *maxaudible); + FMOD_RESULT F_API setMaxAudibleBehavior (FMOD_SOUNDGROUP_BEHAVIOR behavior); + FMOD_RESULT F_API getMaxAudibleBehavior (FMOD_SOUNDGROUP_BEHAVIOR *behavior); + FMOD_RESULT F_API setMuteFadeSpeed (float speed); + FMOD_RESULT F_API getMuteFadeSpeed (float *speed); + FMOD_RESULT F_API setVolume (float volume); + FMOD_RESULT F_API getVolume (float *volume); + FMOD_RESULT F_API stop (); + + // Information only functions. + FMOD_RESULT F_API getName (char *name, int namelen); + FMOD_RESULT F_API getNumSounds (int *numsounds); + FMOD_RESULT F_API getSound (int index, Sound **sound); + FMOD_RESULT F_API getNumPlaying (int *numplaying); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + }; + + class Sound + { + private: + // Constructor made private so user cannot statically instance a Sound class. Appropriate Sound creation or retrieval function must be used. + Sound(); + Sound(const Sound &); + + public: + FMOD_RESULT F_API release (); + FMOD_RESULT F_API getSystemObject (System **system); + + // Standard sound manipulation functions. + FMOD_RESULT F_API lock (unsigned int offset, unsigned int length, void **ptr1, void **ptr2, unsigned int *len1, unsigned int *len2); + FMOD_RESULT F_API unlock (void *ptr1, void *ptr2, unsigned int len1, unsigned int len2); + FMOD_RESULT F_API setDefaults (float frequency, int priority); + FMOD_RESULT F_API getDefaults (float *frequency, int *priority); + FMOD_RESULT F_API set3DMinMaxDistance (float min, float max); + FMOD_RESULT F_API get3DMinMaxDistance (float *min, float *max); + FMOD_RESULT F_API set3DConeSettings (float insideconeangle, float outsideconeangle, float outsidevolume); + FMOD_RESULT F_API get3DConeSettings (float *insideconeangle, float *outsideconeangle, float *outsidevolume); + FMOD_RESULT F_API set3DCustomRolloff (FMOD_VECTOR *points, int numpoints); + FMOD_RESULT F_API get3DCustomRolloff (FMOD_VECTOR **points, int *numpoints); + FMOD_RESULT F_API getSubSound (int index, Sound **subsound); + FMOD_RESULT F_API getSubSoundParent (Sound **parentsound); + FMOD_RESULT F_API getName (char *name, int namelen); + FMOD_RESULT F_API getLength (unsigned int *length, FMOD_TIMEUNIT lengthtype); + FMOD_RESULT F_API getFormat (FMOD_SOUND_TYPE *type, FMOD_SOUND_FORMAT *format, int *channels, int *bits); + FMOD_RESULT F_API getNumSubSounds (int *numsubsounds); + FMOD_RESULT F_API getNumTags (int *numtags, int *numtagsupdated); + FMOD_RESULT F_API getTag (const char *name, int index, FMOD_TAG *tag); + FMOD_RESULT F_API getOpenState (FMOD_OPENSTATE *openstate, unsigned int *percentbuffered, bool *starving, bool *diskbusy); + FMOD_RESULT F_API readData (void *buffer, unsigned int length, unsigned int *read); + FMOD_RESULT F_API seekData (unsigned int pcm); + + FMOD_RESULT F_API setSoundGroup (SoundGroup *soundgroup); + FMOD_RESULT F_API getSoundGroup (SoundGroup **soundgroup); + + // Synchronization point API. These points can come from markers embedded in wav files, and can also generate channel callbacks. + FMOD_RESULT F_API getNumSyncPoints (int *numsyncpoints); + FMOD_RESULT F_API getSyncPoint (int index, FMOD_SYNCPOINT **point); + FMOD_RESULT F_API getSyncPointInfo (FMOD_SYNCPOINT *point, char *name, int namelen, unsigned int *offset, FMOD_TIMEUNIT offsettype); + FMOD_RESULT F_API addSyncPoint (unsigned int offset, FMOD_TIMEUNIT offsettype, const char *name, FMOD_SYNCPOINT **point); + FMOD_RESULT F_API deleteSyncPoint (FMOD_SYNCPOINT *point); + + // Functions also in Channel class but here they are the 'default' to save having to change it in Channel all the time. + FMOD_RESULT F_API setMode (FMOD_MODE mode); + FMOD_RESULT F_API getMode (FMOD_MODE *mode); + FMOD_RESULT F_API setLoopCount (int loopcount); + FMOD_RESULT F_API getLoopCount (int *loopcount); + FMOD_RESULT F_API setLoopPoints (unsigned int loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int loopend, FMOD_TIMEUNIT loopendtype); + FMOD_RESULT F_API getLoopPoints (unsigned int *loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int *loopend, FMOD_TIMEUNIT loopendtype); + + // For MOD/S3M/XM/IT/MID sequenced formats only. + FMOD_RESULT F_API getMusicNumChannels (int *numchannels); + FMOD_RESULT F_API setMusicChannelVolume (int channel, float volume); + FMOD_RESULT F_API getMusicChannelVolume (int channel, float *volume); + FMOD_RESULT F_API setMusicSpeed (float speed); + FMOD_RESULT F_API getMusicSpeed (float *speed); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + }; + + class Reverb3D + { + private: + // Constructor made private so user cannot statically instance a Reverb3D class. Appropriate Reverb creation or retrieval function must be used. + Reverb3D(); + Reverb3D(const Reverb3D &); + + public: + FMOD_RESULT F_API release (); + + // Reverb manipulation. + FMOD_RESULT F_API set3DAttributes (const FMOD_VECTOR *position, float mindistance, float maxdistance); + FMOD_RESULT F_API get3DAttributes (FMOD_VECTOR *position, float *mindistance,float *maxdistance); + FMOD_RESULT F_API setProperties (const FMOD_REVERB_PROPERTIES *properties); + FMOD_RESULT F_API getProperties (FMOD_REVERB_PROPERTIES *properties); + FMOD_RESULT F_API setActive (bool active); + FMOD_RESULT F_API getActive (bool *active); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + }; + + class Geometry + { + private: + // Constructor made private so user cannot statically instance a Geometry class. Appropriate Geometry creation or retrieval function must be used. + Geometry(); + Geometry(const Geometry &); + + public: + FMOD_RESULT F_API release (); + + // Polygon manipulation. + FMOD_RESULT F_API addPolygon (float directocclusion, float reverbocclusion, bool doublesided, int numvertices, const FMOD_VECTOR *vertices, int *polygonindex); + FMOD_RESULT F_API getNumPolygons (int *numpolygons); + FMOD_RESULT F_API getMaxPolygons (int *maxpolygons, int *maxvertices); + FMOD_RESULT F_API getPolygonNumVertices (int index, int *numvertices); + FMOD_RESULT F_API setPolygonVertex (int index, int vertexindex, const FMOD_VECTOR *vertex); + FMOD_RESULT F_API getPolygonVertex (int index, int vertexindex, FMOD_VECTOR *vertex); + FMOD_RESULT F_API setPolygonAttributes (int index, float directocclusion, float reverbocclusion, bool doublesided); + FMOD_RESULT F_API getPolygonAttributes (int index, float *directocclusion, float *reverbocclusion, bool *doublesided); + + // Object manipulation. + FMOD_RESULT F_API setActive (bool active); + FMOD_RESULT F_API getActive (bool *active); + FMOD_RESULT F_API setRotation (const FMOD_VECTOR *forward, const FMOD_VECTOR *up); + FMOD_RESULT F_API getRotation (FMOD_VECTOR *forward, FMOD_VECTOR *up); + FMOD_RESULT F_API setPosition (const FMOD_VECTOR *position); + FMOD_RESULT F_API getPosition (FMOD_VECTOR *position); + FMOD_RESULT F_API setScale (const FMOD_VECTOR *scale); + FMOD_RESULT F_API getScale (FMOD_VECTOR *scale); + FMOD_RESULT F_API save (void *data, int *datasize); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + }; + + #define FMOD_SYSTEM_CALLBACK_ALL 0xFFFFFFFF + class System + { + private: + // Constructor made private so user cannot statically instance a System class. System_Create must be used. + System(); + System(const System &); + + public: + FMOD_RESULT F_API release (); + + // Setup functions. + FMOD_RESULT F_API setOutput (FMOD_OUTPUTTYPE output); + FMOD_RESULT F_API getOutput (FMOD_OUTPUTTYPE *output); + FMOD_RESULT F_API getNumDrivers (int *numdrivers); + FMOD_RESULT F_API getDriverInfo (int id, char *name, int namelen, FMOD_GUID *guid, int *systemrate, FMOD_SPEAKERMODE *speakermode, int *speakermodechannels); + FMOD_RESULT F_API setDriver (int driver); + FMOD_RESULT F_API getDriver (int *driver); + FMOD_RESULT F_API setSoftwareChannels (int numsoftwarechannels); + FMOD_RESULT F_API getSoftwareChannels (int *numsoftwarechannels); + FMOD_RESULT F_API setSoftwareFormat (int samplerate, FMOD_SPEAKERMODE speakermode, int numrawspeakers); + FMOD_RESULT F_API getSoftwareFormat (int *samplerate, FMOD_SPEAKERMODE *speakermode, int *numrawspeakers); + FMOD_RESULT F_API setDSPBufferSize (unsigned int bufferlength, int numbuffers); + FMOD_RESULT F_API getDSPBufferSize (unsigned int *bufferlength, int *numbuffers); + FMOD_RESULT F_API setFileSystem (FMOD_FILE_OPEN_CALLBACK useropen, FMOD_FILE_CLOSE_CALLBACK userclose, FMOD_FILE_READ_CALLBACK userread, FMOD_FILE_SEEK_CALLBACK userseek, FMOD_FILE_ASYNCREAD_CALLBACK userasyncread, FMOD_FILE_ASYNCCANCEL_CALLBACK userasynccancel, int blockalign); + FMOD_RESULT F_API attachFileSystem (FMOD_FILE_OPEN_CALLBACK useropen, FMOD_FILE_CLOSE_CALLBACK userclose, FMOD_FILE_READ_CALLBACK userread, FMOD_FILE_SEEK_CALLBACK userseek); + FMOD_RESULT F_API setAdvancedSettings (FMOD_ADVANCEDSETTINGS *settings); + FMOD_RESULT F_API getAdvancedSettings (FMOD_ADVANCEDSETTINGS *settings); + FMOD_RESULT F_API setCallback (FMOD_SYSTEM_CALLBACK callback, FMOD_SYSTEM_CALLBACK_TYPE callbackmask = FMOD_SYSTEM_CALLBACK_ALL); + + // Plug-in support. + FMOD_RESULT F_API setPluginPath (const char *path); + FMOD_RESULT F_API loadPlugin (const char *filename, unsigned int *handle, unsigned int priority = 0); + FMOD_RESULT F_API unloadPlugin (unsigned int handle); + FMOD_RESULT F_API getNumNestedPlugins (unsigned int handle, int *count); + FMOD_RESULT F_API getNestedPlugin (unsigned int handle, int index, unsigned int *nestedhandle); + FMOD_RESULT F_API getNumPlugins (FMOD_PLUGINTYPE plugintype, int *numplugins); + FMOD_RESULT F_API getPluginHandle (FMOD_PLUGINTYPE plugintype, int index, unsigned int *handle); + FMOD_RESULT F_API getPluginInfo (unsigned int handle, FMOD_PLUGINTYPE *plugintype, char *name, int namelen, unsigned int *version); + FMOD_RESULT F_API setOutputByPlugin (unsigned int handle); + FMOD_RESULT F_API getOutputByPlugin (unsigned int *handle); + FMOD_RESULT F_API createDSPByPlugin (unsigned int handle, DSP **dsp); + FMOD_RESULT F_API getDSPInfoByPlugin (unsigned int handle, const FMOD_DSP_DESCRIPTION **description); + FMOD_RESULT F_API registerCodec (FMOD_CODEC_DESCRIPTION *description, unsigned int *handle, unsigned int priority = 0); + FMOD_RESULT F_API registerDSP (const FMOD_DSP_DESCRIPTION *description, unsigned int *handle); + FMOD_RESULT F_API registerOutput (const FMOD_OUTPUT_DESCRIPTION *description, unsigned int *handle); + + // Init/Close. + FMOD_RESULT F_API init (int maxchannels, FMOD_INITFLAGS flags, void *extradriverdata); + FMOD_RESULT F_API close (); + + // General post-init system functions. + FMOD_RESULT F_API update (); /* IMPORTANT! CALL THIS ONCE PER FRAME! */ + + FMOD_RESULT F_API setSpeakerPosition (FMOD_SPEAKER speaker, float x, float y, bool active); + FMOD_RESULT F_API getSpeakerPosition (FMOD_SPEAKER speaker, float *x, float *y, bool *active); + FMOD_RESULT F_API setStreamBufferSize (unsigned int filebuffersize, FMOD_TIMEUNIT filebuffersizetype); + FMOD_RESULT F_API getStreamBufferSize (unsigned int *filebuffersize, FMOD_TIMEUNIT *filebuffersizetype); + FMOD_RESULT F_API set3DSettings (float dopplerscale, float distancefactor, float rolloffscale); + FMOD_RESULT F_API get3DSettings (float *dopplerscale, float *distancefactor, float *rolloffscale); + FMOD_RESULT F_API set3DNumListeners (int numlisteners); + FMOD_RESULT F_API get3DNumListeners (int *numlisteners); + FMOD_RESULT F_API set3DListenerAttributes (int listener, const FMOD_VECTOR *pos, const FMOD_VECTOR *vel, const FMOD_VECTOR *forward, const FMOD_VECTOR *up); + FMOD_RESULT F_API get3DListenerAttributes (int listener, FMOD_VECTOR *pos, FMOD_VECTOR *vel, FMOD_VECTOR *forward, FMOD_VECTOR *up); + FMOD_RESULT F_API set3DRolloffCallback (FMOD_3D_ROLLOFF_CALLBACK callback); + FMOD_RESULT F_API mixerSuspend (); + FMOD_RESULT F_API mixerResume (); + FMOD_RESULT F_API getDefaultMixMatrix (FMOD_SPEAKERMODE sourcespeakermode, FMOD_SPEAKERMODE targetspeakermode, float *matrix, int matrixhop); + FMOD_RESULT F_API getSpeakerModeChannels (FMOD_SPEAKERMODE mode, int *channels); + + // System information functions. + FMOD_RESULT F_API getVersion (unsigned int *version); + FMOD_RESULT F_API getOutputHandle (void **handle); + FMOD_RESULT F_API getChannelsPlaying (int *channels, int *realchannels = 0); + FMOD_RESULT F_API getCPUUsage (float *dsp, float *stream, float *geometry, float *update, float *total); + FMOD_RESULT F_API getFileUsage (long long *sampleBytesRead, long long *streamBytesRead, long long *otherBytesRead); + + // Sound/DSP/Channel/FX creation and retrieval. + FMOD_RESULT F_API createSound (const char *name_or_data, FMOD_MODE mode, FMOD_CREATESOUNDEXINFO *exinfo, Sound **sound); + FMOD_RESULT F_API createStream (const char *name_or_data, FMOD_MODE mode, FMOD_CREATESOUNDEXINFO *exinfo, Sound **sound); + FMOD_RESULT F_API createDSP (const FMOD_DSP_DESCRIPTION *description, DSP **dsp); + FMOD_RESULT F_API createDSPByType (FMOD_DSP_TYPE type, DSP **dsp); + FMOD_RESULT F_API createChannelGroup (const char *name, ChannelGroup **channelgroup); + FMOD_RESULT F_API createSoundGroup (const char *name, SoundGroup **soundgroup); + FMOD_RESULT F_API createReverb3D (Reverb3D **reverb); + + FMOD_RESULT F_API playSound (Sound *sound, ChannelGroup *channelgroup, bool paused, Channel **channel); + FMOD_RESULT F_API playDSP (DSP *dsp, ChannelGroup *channelgroup, bool paused, Channel **channel); + FMOD_RESULT F_API getChannel (int channelid, Channel **channel); + FMOD_RESULT F_API getMasterChannelGroup (ChannelGroup **channelgroup); + FMOD_RESULT F_API getMasterSoundGroup (SoundGroup **soundgroup); + + // Routing to ports. + FMOD_RESULT F_API attachChannelGroupToPort (FMOD_PORT_TYPE portType, FMOD_PORT_INDEX portIndex, ChannelGroup *channelgroup, bool passThru = false); + FMOD_RESULT F_API detachChannelGroupFromPort (ChannelGroup *channelgroup); + + // Reverb API. + FMOD_RESULT F_API setReverbProperties (int instance, const FMOD_REVERB_PROPERTIES *prop); + FMOD_RESULT F_API getReverbProperties (int instance, FMOD_REVERB_PROPERTIES *prop); + + // System level DSP functionality. + FMOD_RESULT F_API lockDSP (); + FMOD_RESULT F_API unlockDSP (); + + // Recording API. + FMOD_RESULT F_API getRecordNumDrivers (int *numdrivers, int *numconnected); + FMOD_RESULT F_API getRecordDriverInfo (int id, char *name, int namelen, FMOD_GUID *guid, int *systemrate, FMOD_SPEAKERMODE *speakermode, int *speakermodechannels, FMOD_DRIVER_STATE *state); + FMOD_RESULT F_API getRecordPosition (int id, unsigned int *position); + FMOD_RESULT F_API recordStart (int id, Sound *sound, bool loop); + FMOD_RESULT F_API recordStop (int id); + FMOD_RESULT F_API isRecording (int id, bool *recording); + + // Geometry API. + FMOD_RESULT F_API createGeometry (int maxpolygons, int maxvertices, Geometry **geometry); + FMOD_RESULT F_API setGeometrySettings (float maxworldsize); + FMOD_RESULT F_API getGeometrySettings (float *maxworldsize); + FMOD_RESULT F_API loadGeometry (const void *data, int datasize, Geometry **geometry); + FMOD_RESULT F_API getGeometryOcclusion (const FMOD_VECTOR *listener, const FMOD_VECTOR *source, float *direct, float *reverb); + + // Network functions. + FMOD_RESULT F_API setNetworkProxy (const char *proxy); + FMOD_RESULT F_API getNetworkProxy (char *proxy, int proxylen); + FMOD_RESULT F_API setNetworkTimeout (int timeout); + FMOD_RESULT F_API getNetworkTimeout (int *timeout); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + }; + + class ChannelControl + { + private: + // Constructor made private so user cannot statically instance a Control class. + ChannelControl(); + ChannelControl(const ChannelControl &); + + public: + FMOD_RESULT F_API getSystemObject (System **system); + + // General control functionality for Channels and ChannelGroups. + FMOD_RESULT F_API stop (); + FMOD_RESULT F_API setPaused (bool paused); + FMOD_RESULT F_API getPaused (bool *paused); + FMOD_RESULT F_API setVolume (float volume); + FMOD_RESULT F_API getVolume (float *volume); + FMOD_RESULT F_API setVolumeRamp (bool ramp); + FMOD_RESULT F_API getVolumeRamp (bool *ramp); + FMOD_RESULT F_API getAudibility (float *audibility); + FMOD_RESULT F_API setPitch (float pitch); + FMOD_RESULT F_API getPitch (float *pitch); + FMOD_RESULT F_API setMute (bool mute); + FMOD_RESULT F_API getMute (bool *mute); + FMOD_RESULT F_API setReverbProperties (int instance, float wet); + FMOD_RESULT F_API getReverbProperties (int instance, float *wet); + FMOD_RESULT F_API setLowPassGain (float gain); + FMOD_RESULT F_API getLowPassGain (float *gain); + FMOD_RESULT F_API setMode (FMOD_MODE mode); + FMOD_RESULT F_API getMode (FMOD_MODE *mode); + FMOD_RESULT F_API setCallback (FMOD_CHANNELCONTROL_CALLBACK callback); + FMOD_RESULT F_API isPlaying (bool *isplaying); + + // Panning and level adjustment. + // Note all 'set' functions alter a final matrix, this is why the only get function is getMixMatrix, to avoid other get functions returning incorrect/obsolete values. + FMOD_RESULT F_API setPan (float pan); + FMOD_RESULT F_API setMixLevelsOutput (float frontleft, float frontright, float center, float lfe, float surroundleft, float surroundright, float backleft, float backright); + FMOD_RESULT F_API setMixLevelsInput (float *levels, int numlevels); + FMOD_RESULT F_API setMixMatrix (float *matrix, int outchannels, int inchannels, int inchannel_hop = 0); + FMOD_RESULT F_API getMixMatrix (float *matrix, int *outchannels, int *inchannels, int inchannel_hop = 0); + + // Clock based functionality. + FMOD_RESULT F_API getDSPClock (unsigned long long *dspclock, unsigned long long *parentclock); + FMOD_RESULT F_API setDelay (unsigned long long dspclock_start, unsigned long long dspclock_end, bool stopchannels = true); + FMOD_RESULT F_API getDelay (unsigned long long *dspclock_start, unsigned long long *dspclock_end, bool *stopchannels = 0); + FMOD_RESULT F_API addFadePoint (unsigned long long dspclock, float volume); + FMOD_RESULT F_API setFadePointRamp (unsigned long long dspclock, float volume); + FMOD_RESULT F_API removeFadePoints (unsigned long long dspclock_start, unsigned long long dspclock_end); + FMOD_RESULT F_API getFadePoints (unsigned int *numpoints, unsigned long long *point_dspclock, float *point_volume); + + // DSP effects. + FMOD_RESULT F_API getDSP (int index, DSP **dsp); + FMOD_RESULT F_API addDSP (int index, DSP *dsp); + FMOD_RESULT F_API removeDSP (DSP *dsp); + FMOD_RESULT F_API getNumDSPs (int *numdsps); + FMOD_RESULT F_API setDSPIndex (DSP *dsp, int index); + FMOD_RESULT F_API getDSPIndex (DSP *dsp, int *index); + + // 3D functionality. + FMOD_RESULT F_API set3DAttributes (const FMOD_VECTOR *pos, const FMOD_VECTOR *vel); + FMOD_RESULT F_API get3DAttributes (FMOD_VECTOR *pos, FMOD_VECTOR *vel); + FMOD_RESULT F_API set3DMinMaxDistance (float mindistance, float maxdistance); + FMOD_RESULT F_API get3DMinMaxDistance (float *mindistance, float *maxdistance); + FMOD_RESULT F_API set3DConeSettings (float insideconeangle, float outsideconeangle, float outsidevolume); + FMOD_RESULT F_API get3DConeSettings (float *insideconeangle, float *outsideconeangle, float *outsidevolume); + FMOD_RESULT F_API set3DConeOrientation (FMOD_VECTOR *orientation); + FMOD_RESULT F_API get3DConeOrientation (FMOD_VECTOR *orientation); + FMOD_RESULT F_API set3DCustomRolloff (FMOD_VECTOR *points, int numpoints); + FMOD_RESULT F_API get3DCustomRolloff (FMOD_VECTOR **points, int *numpoints); + FMOD_RESULT F_API set3DOcclusion (float directocclusion, float reverbocclusion); + FMOD_RESULT F_API get3DOcclusion (float *directocclusion, float *reverbocclusion); + FMOD_RESULT F_API set3DSpread (float angle); + FMOD_RESULT F_API get3DSpread (float *angle); + FMOD_RESULT F_API set3DLevel (float level); + FMOD_RESULT F_API get3DLevel (float *level); + FMOD_RESULT F_API set3DDopplerLevel (float level); + FMOD_RESULT F_API get3DDopplerLevel (float *level); + FMOD_RESULT F_API set3DDistanceFilter (bool custom, float customLevel, float centerFreq); + FMOD_RESULT F_API get3DDistanceFilter (bool *custom, float *customLevel, float *centerFreq); + + // Userdata set/get. + FMOD_RESULT F_API setUserData (void *userdata); + FMOD_RESULT F_API getUserData (void **userdata); + }; + + class Channel : public ChannelControl + { + private: + Channel(); + Channel(const Channel &); + + public: + // Channel specific control functionality. + FMOD_RESULT F_API setFrequency(float frequency); + FMOD_RESULT F_API getFrequency(float *frequency); + FMOD_RESULT F_API setPriority(int priority); + FMOD_RESULT F_API getPriority(int *priority); + FMOD_RESULT F_API setPosition(unsigned int position, FMOD_TIMEUNIT postype); + FMOD_RESULT F_API getPosition(unsigned int *position, FMOD_TIMEUNIT postype); + FMOD_RESULT F_API setChannelGroup(ChannelGroup *channelgroup); + FMOD_RESULT F_API getChannelGroup(ChannelGroup **channelgroup); + FMOD_RESULT F_API setLoopCount(int loopcount); + FMOD_RESULT F_API getLoopCount(int *loopcount); + FMOD_RESULT F_API setLoopPoints(unsigned int loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int loopend, FMOD_TIMEUNIT loopendtype); + FMOD_RESULT F_API getLoopPoints(unsigned int *loopstart, FMOD_TIMEUNIT loopstarttype, unsigned int *loopend, FMOD_TIMEUNIT loopendtype); + + // Information only functions. + FMOD_RESULT F_API isVirtual(bool *isvirtual); + FMOD_RESULT F_API getCurrentSound(Sound ** sound); + FMOD_RESULT F_API getIndex(int *index); + }; + + class ChannelGroup : public ChannelControl + { + private: + // Constructor made private so user cannot statically instance a ChannelGroup class. Appropriate ChannelGroup creation or retrieval function must be used. + ChannelGroup(); + ChannelGroup(const ChannelGroup &); + + public: + FMOD_RESULT F_API release (); + + // Nested channel groups. + FMOD_RESULT F_API addGroup (ChannelGroup *group, bool propagatedspclock = true, DSPConnection **connection = 0); + FMOD_RESULT F_API getNumGroups (int *numgroups); + FMOD_RESULT F_API getGroup (int index, ChannelGroup **group); + FMOD_RESULT F_API getParentGroup (ChannelGroup **group); + + // Information only functions. + FMOD_RESULT F_API getName (char *name, int namelen); + FMOD_RESULT F_API getNumChannels (int *numchannels); + FMOD_RESULT F_API getChannel (int index, Channel **channel); + }; +} diff --git a/broma_ida/types/helpers.hpp b/broma_ida/types/helpers.hpp new file mode 100644 index 0000000..898aba9 --- /dev/null +++ b/broma_ida/types/helpers.hpp @@ -0,0 +1,63 @@ + +class SeedValueSR +{ +public: + int seed; + int random; +}; + +class SeedValueRS +{ +public: + int random; + int seed; +}; + + +class SeedValueVRS +{ +public: + int value; + int random; + int seed; +}; + +class SeedValueVSR +{ +public: + int value; + int seed; + int random; +}; + +class SeedValueRVS +{ +public: + int random; + int value; + int seed; +}; + +class SeedValueRSV +{ +public: + int random; + int seed; + int value; +}; + +class SeedValueSVR +{ +public: + int seed; + int value; + int random; +}; + +class SeedValueSRV +{ +public: + int seed; + int random; + int value; +}; diff --git a/broma_ida/types/stl_types.hpp b/broma_ida/types/stl_types.hpp new file mode 100644 index 0000000..a66bc91 --- /dev/null +++ b/broma_ida/types/stl_types.hpp @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include +#include +#include "enums.hpp" + +namespace cocos2d +{ + class CCObject; + class CCArray; +} + +class EnterEffectInstance; +class EffectGameObject; +class SFXTriggerState; +class GameObject; +class DynamicObjectAction; +class SongTriggerState; +class ChanceObject; +class EnhancedGameObject; +struct PlayerButtonCommand; +class EventTriggerInstance; +class AdvancedFollowInstance; +struct SmartPrefabResult; +struct KeyframeObject; +struct SavedActiveObjectState; +struct SavedSpecialObjectState; +struct SavedObjectStateRef; +struct SFXTriggerInstance; +struct GameObjectEditorState; +struct GJValueTween; +struct SongChannelState; +struct GJPointDouble; +struct GameObjectPhysics; + +class holy_shit +{ +public: + std::string m_str; + + std::vector m_m0; + std::vector m_m1; + std::vector m_m2; + std::vector m_m3; + std::vector m_m4; + std::vector m_m5; + std::vector m_m6; + std::vector m_m7; + std::vector m_m8; + std::vector m_m9; + std::vector m_m10; + std::vector m_m11; + std::vector m_m12; + std::vector*>*> m_m13; + std::vector*> m_m14; + std::vector m_m15; + std::vector m_m16; + std::vector m_m17; + std::vector m_m18; + std::vector m_m19; + std::vector m_m20; + std::vector m_m21; + std::vector m_m22; + std::vector m_m23; + + std::map m_m24; + std::map, int> m_m25; + std::map m_m26; + std::map m_m27; + std::map m_m28; + std::map m_m29; + std::map, int> m_m30; + std::map m_m31; + std::map, SFXTriggerInstance> m_m32; + std::map> m_m33; + std::map> m_m34; + std::map m_m35; + std::map, std::vector> m_m36; + + std::unordered_map m_m37; + std::unordered_map> m_m38; + std::unordered_map m_m39; + std::unordered_map> m_m40; + std::unordered_map m_m41; + std::unordered_map> m_m42; + std::unordered_map> m_m43; + std::unordered_map m_m44; + std::unordered_map m_m45; + std::unordered_map m_m46; + std::unordered_map m_m47; + std::unordered_map m_m48; + std::unordered_map m_m49; + std::unordered_map> m_m50; + std::unordered_map> m_m51; + std::unordered_map> m_m52; + std::unordered_map m_m53; + std::unordered_map m_m54; + + std::set m_m55; + + std::unordered_set m_m56; +}; diff --git a/broma_ida/utils.py b/broma_ida/utils.py index 8970f0c..0e3cd8b 100644 --- a/broma_ida/utils.py +++ b/broma_ida/utils.py @@ -1,4 +1,4 @@ -from typing import get_args, NoReturn, Union +from typing import get_args, Union, NoReturn, Optional from idaapi import ( get_imagebase, get_inf_structure, get_file_type_name, @@ -9,34 +9,31 @@ from ida_name import get_name_ea from idc import set_name +from sys import path as sys_path +from os import path as os_path from re import sub +from pathlib import Path -from pybroma import Type - -from broma_ida.broma.constants import BROMA_PLATFORMS +from broma_ida.broma.constants import ( + BROMA_PLATFORMS, CPP_TYPE_QUALIFIERS, CPP_DATA_TYPES, + CPP_PRIMITIVES +) from broma_ida.broma.binding import Binding +from broma_ida.broma.argtype import ArgType -CPP_TYPE_SPECIFIERS = ("unsigned", "signed") -CPP_TYPE_QUALIFIERS = ("const", "volatile") -CPP_DATA_TYPES = ("bool", "char", "short", "int", "long") -CPP_PRIMITIVES = ( - "void", "int", "char", "float", "short", - "double", "bool", "long" -) - -g_platform: BROMA_PLATFORMS = "" # type: ignore +g_platform: Optional[BROMA_PLATFORMS] = None -def stop(reason: Union[str, None] = None) -> NoReturn: +def stop(reason: Optional[str] = None) -> NoReturn: """Nuh Uh""" raise Exception() if reason is None else Exception(reason) def popup( button1: str, - button2: Union[str, None], - button3: Union[str, None], + button2: Optional[str], + button3: Optional[str], text: str, default: int = 1 ) -> int: @@ -111,9 +108,7 @@ def get_short_info(binding: Binding) -> str: Returns: str: In the format of "[binding name] @ [binding address]" """ - return f"""{ - binding["qualifiedName"] - } @ {hex(binding["address"])}""" # type: ignore + return f"""{binding["qualified_name"]} @ {hex(binding["address"])}""" def get_platform() -> Union[BROMA_PLATFORMS, NoReturn]: @@ -123,17 +118,23 @@ def get_platform() -> Union[BROMA_PLATFORMS, NoReturn]: not able to be determined """ global g_platform + if g_platform is not None: + return g_platform + structure_info = get_inf_structure() if structure_info.filetype == f_PE: + g_platform = "win" return "win" if structure_info.filetype == f_MACHO: file_type_name = get_file_type_name() if file_type_name.endswith("ARM64"): + g_platform = "ios" return "ios" elif file_type_name.endswith("X86_64"): + g_platform = "mac" return "mac" if g_platform == "": @@ -145,7 +146,9 @@ def get_platform() -> Union[BROMA_PLATFORMS, NoReturn]: if platform not in get_args(BROMA_PLATFORMS): popup( "Ok", None, None, - f"""Invalid platform! ({platform} not "win", "mac" or "ios")""" + f"""Invalid platform! ("{platform}" not in ("{ + get_args(BROMA_PLATFORMS) + }\"))""" ) stop() @@ -170,14 +173,13 @@ def get_platform_printable(platform: BROMA_PLATFORMS) -> str: return platform_to_printable[platform] -def are_args_primitive(arguments: dict[str, Type]) -> bool: +def are_args_primitive(arguments: dict[str, ArgType]) -> bool: """Checks if the arguments are all primitives because importing structs isn't supported yet TODO: start importing structs :D Args: - arguments (dict[str, Type]): - FunctionBindField.MemberFunctionProto::args + arguments (dict[str, str]) Returns: bool: ya @@ -191,7 +193,7 @@ def are_args_primitive(arguments: dict[str, Type]) -> bool: return True arguments_str = { - name: arg_type.name for name, arg_type in arguments.items() + name: t["type"] for name, t in arguments.items() } for name, arg_type in arguments_str.items(): @@ -212,4 +214,34 @@ def are_args_primitive(arguments: dict[str, Type]) -> bool: arguments_str[name] = remove_pointer_or_reference(arguments_str[name]) - return all([arg_type in CPP_PRIMITIVES for _, arg_type in arguments_str.items()]) + return all([ + arg_type in CPP_PRIMITIVES for _, arg_type in arguments_str.items() + ]) + + +def is_primitive_type(ret: str) -> bool: + """Is a type a C++ primitive + + Args: + ret (str): ya + + Returns: + bool: ya + """ + return ret in CPP_PRIMITIVES + + +def get_ida_plugin_path() -> Optional[Path]: + """_summary_ + + Returns: + str: _description_ + """ + paths = [path for path in sys_path if "plugins" in path] + + if len(paths) != 1: + return None + + return Path( + os_path.abspath(os_path.join(os_path.dirname(paths[0]), "plugins")) + )