GenerateWebGLRenderingContext.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. /*
  2. * Copyright (c) 2024, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  3. * Copyright (c) 2024, Luke Wilde <luke@ladybird.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "BindingsGenerator/IDLGenerators.h"
  8. #include <AK/LexicalPath.h>
  9. #include <AK/SourceGenerator.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibCore/ArgsParser.h>
  12. #include <LibCore/File.h>
  13. #include <LibIDL/IDLParser.h>
  14. #include <LibMain/Main.h>
  15. static bool is_webgl_object_type(StringView type_name)
  16. {
  17. return type_name == "WebGLBuffer"sv
  18. || type_name == "WebGLFramebuffer"sv
  19. || type_name == "WebGLProgram"sv
  20. || type_name == "WebGLRenderbuffer"sv
  21. || type_name == "WebGLShader"sv
  22. || type_name == "WebGLTexture"sv
  23. || type_name == "WebGLUniformLocation"sv;
  24. }
  25. static bool gl_function_modifies_framebuffer(StringView function_name)
  26. {
  27. return function_name == "clearColor"sv || function_name == "drawArrays"sv || function_name == "drawElements"sv;
  28. }
  29. static ByteString to_cpp_type(const IDL::Type& type, const IDL::Interface& interface)
  30. {
  31. if (type.name() == "undefined"sv)
  32. return "void"sv;
  33. if (type.name() == "object"sv) {
  34. if (type.is_nullable())
  35. return "JS::Object*"sv;
  36. return "JS::Object&"sv;
  37. }
  38. if (type.name() == "DOMString"sv) {
  39. if (type.is_nullable())
  40. return "Optional<String>"sv;
  41. return "String"sv;
  42. }
  43. auto cpp_type = idl_type_name_to_cpp_type(type, interface);
  44. return cpp_type.name;
  45. }
  46. static ByteString idl_to_gl_function_name(StringView function_name)
  47. {
  48. StringBuilder gl_function_name_builder;
  49. gl_function_name_builder.append("gl"sv);
  50. for (size_t i = 0; i < function_name.length(); ++i) {
  51. if (i == 0) {
  52. gl_function_name_builder.append(to_ascii_uppercase(function_name[i]));
  53. } else {
  54. gl_function_name_builder.append(function_name[i]);
  55. }
  56. }
  57. if (function_name == "clearDepth"sv || function_name == "depthRange"sv) {
  58. gl_function_name_builder.append("f"sv);
  59. }
  60. return gl_function_name_builder.to_byte_string();
  61. }
  62. struct NameAndType {
  63. StringView name;
  64. struct {
  65. StringView type;
  66. int element_count { 0 };
  67. } return_type;
  68. };
  69. static void generate_get_parameter(SourceGenerator& generator)
  70. {
  71. Vector<NameAndType> const name_to_type = {
  72. { "ACTIVE_TEXTURE"sv, { "GLenum"sv } },
  73. { "ALIASED_LINE_WIDTH_RANGE"sv, { "Float32Array"sv, 2 } },
  74. { "ALIASED_POINT_SIZE_RANGE"sv, { "Float32Array"sv, 2 } },
  75. { "ALPHA_BITS"sv, { "GLint"sv } },
  76. { "ARRAY_BUFFER_BINDING"sv, { "WebGLBuffer"sv } },
  77. { "BLEND"sv, { "GLboolean"sv } },
  78. { "BLEND_COLOR"sv, { "Float32Array"sv, 4 } },
  79. { "BLEND_DST_ALPHA"sv, { "GLenum"sv } },
  80. { "BLEND_DST_RGB"sv, { "GLenum"sv } },
  81. { "BLEND_EQUATION_ALPHA"sv, { "GLenum"sv } },
  82. { "BLEND_EQUATION_RGB"sv, { "GLenum"sv } },
  83. { "BLEND_SRC_ALPHA"sv, { "GLenum"sv } },
  84. { "BLEND_SRC_RGB"sv, { "GLenum"sv } },
  85. { "BLUE_BITS"sv, { "GLint"sv } },
  86. { "COLOR_CLEAR_VALUE"sv, { "Float32Array"sv, 4 } },
  87. // FIXME: { "COLOR_WRITEMASK"sv, { "sequence<GLboolean>"sv, 4 } },
  88. // FIXME: { "COMPRESSED_TEXTURE_FORMATS"sv, { "Uint32Array"sv } },
  89. { "CULL_FACE"sv, { "GLboolean"sv } },
  90. { "CULL_FACE_MODE"sv, { "GLenum"sv } },
  91. { "CURRENT_PROGRAM"sv, { "WebGLProgram"sv } },
  92. { "DEPTH_BITS"sv, { "GLint"sv } },
  93. { "DEPTH_CLEAR_VALUE"sv, { "GLfloat"sv } },
  94. { "DEPTH_FUNC"sv, { "GLenum"sv } },
  95. { "DEPTH_RANGE"sv, { "Float32Array"sv, 2 } },
  96. { "DEPTH_TEST"sv, { "GLboolean"sv } },
  97. { "DEPTH_WRITEMASK"sv, { "GLboolean"sv } },
  98. { "DITHER"sv, { "GLboolean"sv } },
  99. { "ELEMENT_ARRAY_BUFFER_BINDING"sv, { "WebGLBuffer"sv } },
  100. { "FRAMEBUFFER_BINDING"sv, { "WebGLFramebuffer"sv } },
  101. { "FRONT_FACE"sv, { "GLenum"sv } },
  102. { "GENERATE_MIPMAP_HINT"sv, { "GLenum"sv } },
  103. { "GREEN_BITS"sv, { "GLint"sv } },
  104. { "IMPLEMENTATION_COLOR_READ_FORMAT"sv, { "GLenum"sv } },
  105. { "IMPLEMENTATION_COLOR_READ_TYPE"sv, { "GLenum"sv } },
  106. { "LINE_WIDTH"sv, { "GLfloat"sv } },
  107. { "MAX_COMBINED_TEXTURE_IMAGE_UNITS"sv, { "GLint"sv } },
  108. { "MAX_CUBE_MAP_TEXTURE_SIZE"sv, { "GLint"sv } },
  109. { "MAX_FRAGMENT_UNIFORM_VECTORS"sv, { "GLint"sv } },
  110. { "MAX_RENDERBUFFER_SIZE"sv, { "GLint"sv } },
  111. { "MAX_TEXTURE_IMAGE_UNITS"sv, { "GLint"sv } },
  112. { "MAX_TEXTURE_SIZE"sv, { "GLint"sv } },
  113. { "MAX_VARYING_VECTORS"sv, { "GLint"sv } },
  114. { "MAX_VERTEX_ATTRIBS"sv, { "GLint"sv } },
  115. { "MAX_VERTEX_TEXTURE_IMAGE_UNITS"sv, { "GLint"sv } },
  116. { "MAX_VERTEX_UNIFORM_VECTORS"sv, { "GLint"sv } },
  117. { "MAX_VIEWPORT_DIMS"sv, { "Int32Array"sv, 2 } },
  118. { "PACK_ALIGNMENT"sv, { "GLint"sv } },
  119. { "POLYGON_OFFSET_FACTOR"sv, { "GLfloat"sv } },
  120. { "POLYGON_OFFSET_FILL"sv, { "GLboolean"sv } },
  121. { "POLYGON_OFFSET_UNITS"sv, { "GLfloat"sv } },
  122. { "RED_BITS"sv, { "GLint"sv } },
  123. { "RENDERBUFFER_BINDING"sv, { "WebGLRenderbuffer"sv } },
  124. { "RENDERER"sv, { "DOMString"sv } },
  125. { "SAMPLE_ALPHA_TO_COVERAGE"sv, { "GLboolean"sv } },
  126. { "SAMPLE_BUFFERS"sv, { "GLint"sv } },
  127. { "SAMPLE_COVERAGE"sv, { "GLboolean"sv } },
  128. { "SAMPLE_COVERAGE_INVERT"sv, { "GLboolean"sv } },
  129. { "SAMPLE_COVERAGE_VALUE"sv, { "GLfloat"sv } },
  130. { "SAMPLES"sv, { "GLint"sv } },
  131. { "SCISSOR_BOX"sv, { "Int32Array"sv, 4 } },
  132. { "SCISSOR_TEST"sv, { "GLboolean"sv } },
  133. { "SHADING_LANGUAGE_VERSION"sv, { "DOMString"sv } },
  134. { "STENCIL_BACK_FAIL"sv, { "GLenum"sv } },
  135. { "STENCIL_BACK_FUNC"sv, { "GLenum"sv } },
  136. { "STENCIL_BACK_PASS_DEPTH_FAIL"sv, { "GLenum"sv } },
  137. { "STENCIL_BACK_PASS_DEPTH_PASS"sv, { "GLenum"sv } },
  138. { "STENCIL_BACK_REF"sv, { "GLint"sv } },
  139. { "STENCIL_BACK_VALUE_MASK"sv, { "GLuint"sv } },
  140. { "STENCIL_BACK_WRITEMASK"sv, { "GLuint"sv } },
  141. { "STENCIL_BITS"sv, { "GLint"sv } },
  142. { "STENCIL_CLEAR_VALUE"sv, { "GLint"sv } },
  143. { "STENCIL_FAIL"sv, { "GLenum"sv } },
  144. { "STENCIL_FUNC"sv, { "GLenum"sv } },
  145. { "STENCIL_PASS_DEPTH_FAIL"sv, { "GLenum"sv } },
  146. { "STENCIL_PASS_DEPTH_PASS"sv, { "GLenum"sv } },
  147. { "STENCIL_REF"sv, { "GLint"sv } },
  148. { "STENCIL_TEST"sv, { "GLboolean"sv } },
  149. { "STENCIL_VALUE_MASK"sv, { "GLuint"sv } },
  150. { "STENCIL_WRITEMASK"sv, { "GLuint"sv } },
  151. { "SUBPIXEL_BITS"sv, { "GLint"sv } },
  152. { "TEXTURE_BINDING_2D"sv, { "WebGLTexture"sv } },
  153. { "TEXTURE_BINDING_CUBE_MAP"sv, { "WebGLTexture"sv } },
  154. { "UNPACK_ALIGNMENT"sv, { "GLint"sv } },
  155. // FIXME: { "UNPACK_COLORSPACE_CONVERSION_WEBGL"sv, { "GLenum"sv } },
  156. // FIXME: { "UNPACK_FLIP_Y_WEBGL"sv, { "GLboolean"sv } },
  157. // FIXME: { "UNPACK_PREMULTIPLY_ALPHA_WEBGL"sv, { "GLboolean"sv } },
  158. { "VENDOR"sv, { "DOMString"sv } },
  159. { "VERSION"sv, { "DOMString"sv } },
  160. { "VIEWPORT"sv, { "Int32Array"sv, 4 } },
  161. };
  162. auto is_primitive_type = [](StringView type) {
  163. return type == "GLboolean"sv || type == "GLint"sv || type == "GLfloat"sv || type == "GLenum"sv || type == "GLuint"sv;
  164. };
  165. generator.append(" switch (pname) {");
  166. for (auto const& name_and_type : name_to_type) {
  167. auto const& parameter_name = name_and_type.name;
  168. auto const& type_name = name_and_type.return_type.type;
  169. StringBuilder string_builder;
  170. SourceGenerator impl_generator { string_builder };
  171. impl_generator.set("parameter_name", parameter_name);
  172. impl_generator.set("type_name", type_name);
  173. impl_generator.append(R"~~~(
  174. case GL_@parameter_name@: {)~~~");
  175. if (is_primitive_type(type_name)) {
  176. impl_generator.append(R"~~~(
  177. GLint result;
  178. glGetIntegerv(GL_@parameter_name@, &result);
  179. return JS::Value(result);
  180. )~~~");
  181. } else if (type_name == "DOMString"sv) {
  182. impl_generator.append(R"~~~(
  183. auto result = reinterpret_cast<const char*>(glGetString(GL_@parameter_name@));
  184. return JS::PrimitiveString::create(m_realm->vm(), ByteString { result });)~~~");
  185. } else if (type_name == "Float32Array"sv || type_name == "Int32Array"sv) {
  186. auto element_count = name_and_type.return_type.element_count;
  187. impl_generator.set("element_count", MUST(String::formatted("{}", element_count)));
  188. if (type_name == "Int32Array"sv) {
  189. impl_generator.set("gl_function_name", "glGetIntegerv"sv);
  190. impl_generator.set("element_type", "GLint"sv);
  191. } else if (type_name == "Float32Array"sv) {
  192. impl_generator.set("gl_function_name", "glGetFloatv"sv);
  193. impl_generator.set("element_type", "GLfloat"sv);
  194. } else {
  195. VERIFY_NOT_REACHED();
  196. }
  197. impl_generator.append(R"~~~(
  198. Array<@element_type@, @element_count@> result;
  199. @gl_function_name@(GL_@parameter_name@, result.data());
  200. auto byte_buffer = MUST(ByteBuffer::copy(result.data(), @element_count@ * sizeof(@element_type@)));
  201. auto array_buffer = JS::ArrayBuffer::create(m_realm, move(byte_buffer));
  202. return JS::@type_name@::create(m_realm, @element_count@, array_buffer);
  203. )~~~");
  204. } else if (type_name == "WebGLProgram"sv || type_name == "WebGLBuffer"sv || type_name == "WebGLTexture"sv || type_name == "WebGLFramebuffer"sv || type_name == "WebGLRenderbuffer"sv) {
  205. impl_generator.append(R"~~~(
  206. GLint result;
  207. glGetIntegerv(GL_@parameter_name@, &result);
  208. if (!result)
  209. return JS::js_null();
  210. return @type_name@::create(m_realm, result);
  211. )~~~");
  212. } else {
  213. VERIFY_NOT_REACHED();
  214. }
  215. impl_generator.append(" }");
  216. generator.append(string_builder.string_view());
  217. }
  218. generator.appendln(R"~~~(
  219. default:
  220. dbgln("Unknown WebGL parameter name: {:x}", pname);
  221. set_error(GL_INVALID_ENUM);
  222. return JS::js_null();
  223. })~~~");
  224. }
  225. static void generate_get_buffer_parameter(SourceGenerator& generator)
  226. {
  227. Vector<NameAndType> const name_to_type = {
  228. { "BUFFER_SIZE"sv, { "GLint"sv } },
  229. { "BUFFER_USAGE"sv, { "GLenum"sv } },
  230. };
  231. generator.append(" switch (pname) {");
  232. for (auto const& name_and_type : name_to_type) {
  233. auto const& parameter_name = name_and_type.name;
  234. auto const& type_name = name_and_type.return_type.type;
  235. StringBuilder string_builder;
  236. SourceGenerator impl_generator { string_builder };
  237. impl_generator.set("parameter_name", parameter_name);
  238. impl_generator.set("type_name", type_name);
  239. impl_generator.append(R"~~~(
  240. case GL_@parameter_name@: {
  241. GLint result;
  242. glGetBufferParameteriv(target, GL_@parameter_name@, &result);
  243. return JS::Value(result);
  244. }
  245. )~~~");
  246. generator.append(string_builder.string_view());
  247. }
  248. generator.appendln(R"~~~(
  249. default:
  250. TODO();
  251. })~~~");
  252. }
  253. ErrorOr<int> serenity_main(Main::Arguments arguments)
  254. {
  255. StringView generated_header_path;
  256. StringView generated_implementation_path;
  257. Vector<ByteString> base_paths;
  258. StringView webgl_context_idl_path;
  259. Core::ArgsParser args_parser;
  260. args_parser.add_option(webgl_context_idl_path, "Path to the WebGLRenderingContext idl file", "webgl-idl-path", 'i', "webgl-idl-path");
  261. args_parser.add_option(Core::ArgsParser::Option {
  262. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  263. .help_string = "Path to root of IDL file tree(s)",
  264. .long_name = "base-path",
  265. .short_name = 'b',
  266. .value_name = "base-path",
  267. .accept_value = [&](StringView s) {
  268. base_paths.append(s);
  269. return true;
  270. },
  271. });
  272. args_parser.add_option(generated_header_path, "Path to the header file to generate", "generated-header-path", 'h', "generated-header-path");
  273. args_parser.add_option(generated_implementation_path, "Path to the implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  274. args_parser.parse(arguments);
  275. auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
  276. auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
  277. auto idl_file = MUST(Core::File::open(webgl_context_idl_path, Core::File::OpenMode::Read));
  278. auto webgl_context_idl_file_content = MUST(idl_file->read_until_eof());
  279. Vector<ByteString> import_base_paths;
  280. for (auto const& base_path : base_paths) {
  281. VERIFY(!base_path.is_empty());
  282. import_base_paths.append(base_path);
  283. }
  284. IDL::Parser parser(webgl_context_idl_path, StringView(webgl_context_idl_file_content), import_base_paths);
  285. auto const& interface = parser.parse();
  286. auto path = LexicalPath(generated_header_path);
  287. auto title = path.title();
  288. auto first_dot = title.find('.');
  289. ByteString class_name = title;
  290. if (first_dot.has_value())
  291. class_name = title.substring_view(0, *first_dot);
  292. StringBuilder header_file_string_builder;
  293. SourceGenerator header_file_generator { header_file_string_builder };
  294. header_file_generator.set("class_name", class_name);
  295. StringBuilder implementation_file_string_builder;
  296. SourceGenerator implementation_file_generator { implementation_file_string_builder };
  297. implementation_file_generator.set("class_name", class_name);
  298. implementation_file_generator.append(R"~~~(
  299. #include <LibJS/Runtime/ArrayBuffer.h>
  300. #include <LibJS/Runtime/DataView.h>
  301. #include <LibJS/Runtime/TypedArray.h>
  302. #include <LibWeb/HTML/HTMLCanvasElement.h>
  303. #include <LibWeb/HTML/HTMLImageElement.h>
  304. #include <LibWeb/HTML/HTMLVideoElement.h>
  305. #include <LibWeb/HTML/ImageBitmap.h>
  306. #include <LibWeb/HTML/ImageData.h>
  307. #include <LibWeb/WebGL/OpenGLContext.h>
  308. #include <LibWeb/WebGL/WebGLActiveInfo.h>
  309. #include <LibWeb/WebGL/WebGLBuffer.h>
  310. #include <LibWeb/WebGL/WebGLFramebuffer.h>
  311. #include <LibWeb/WebGL/WebGLProgram.h>
  312. #include <LibWeb/WebGL/WebGLRenderbuffer.h>
  313. #include <LibWeb/WebGL/@class_name@.h>
  314. #include <LibWeb/WebGL/WebGLShader.h>
  315. #include <LibWeb/WebGL/WebGLShaderPrecisionFormat.h>
  316. #include <LibWeb/WebGL/WebGLTexture.h>
  317. #include <LibWeb/WebGL/WebGLUniformLocation.h>
  318. #include <LibWeb/WebIDL/Buffers.h>
  319. #include <GLES2/gl2.h>
  320. #include <GLES2/gl2ext.h>
  321. namespace Web::WebGL {
  322. static Vector<GLchar> null_terminated_string(StringView string)
  323. {
  324. Vector<GLchar> result;
  325. for (auto c : string.bytes())
  326. result.append(c);
  327. result.append('\\0');
  328. return result;
  329. }
  330. @class_name@::@class_name@(JS::Realm& realm, NonnullOwnPtr<OpenGLContext> context)
  331. : m_realm(realm)
  332. , m_context(move(context))
  333. {
  334. }
  335. )~~~");
  336. header_file_generator.append(R"~~~(
  337. #pragma once
  338. #include <AK/NonnullOwnPtr.h>
  339. #include <LibGC/Ptr.h>
  340. #include <LibGfx/Bitmap.h>
  341. #include <LibWeb/Bindings/PlatformObject.h>
  342. #include <LibWeb/Forward.h>
  343. #include <LibWeb/WebIDL/Types.h>
  344. namespace Web::WebGL {
  345. using namespace Web::HTML;
  346. class @class_name@ {
  347. public:
  348. @class_name@(JS::Realm&, NonnullOwnPtr<OpenGLContext>);
  349. OpenGLContext& context() { return *m_context; }
  350. virtual void present() = 0;
  351. virtual void needs_to_present() = 0;
  352. virtual void set_error(GLenum) = 0;
  353. )~~~");
  354. for (auto const& function : interface.functions) {
  355. if (function.extended_attributes.contains("FIXME")) {
  356. continue;
  357. }
  358. if (function.name == "getSupportedExtensions"sv || function.name == "getExtension"sv || function.name == "getContextAttributes"sv || function.name == "isContextLost"sv) {
  359. // Implemented in WebGLRenderingContext
  360. continue;
  361. }
  362. StringBuilder function_declaration;
  363. StringBuilder function_parameters;
  364. for (size_t i = 0; i < function.parameters.size(); ++i) {
  365. auto const& parameter = function.parameters[i];
  366. function_parameters.append(to_cpp_type(*parameter.type, interface));
  367. function_parameters.append(" "sv);
  368. function_parameters.append(parameter.name);
  369. if (i != function.parameters.size() - 1) {
  370. function_parameters.append(", "sv);
  371. }
  372. }
  373. auto function_name = function.name.to_snakecase();
  374. function_declaration.append(to_cpp_type(*function.return_type, interface));
  375. function_declaration.append(" "sv);
  376. function_declaration.append(function_name);
  377. function_declaration.append("("sv);
  378. function_declaration.append(function_parameters.string_view());
  379. function_declaration.append(");"sv);
  380. header_file_generator.append(" "sv);
  381. header_file_generator.append(function_declaration.string_view());
  382. header_file_generator.append("\n"sv);
  383. StringBuilder function_impl;
  384. SourceGenerator function_impl_generator { function_impl };
  385. function_impl_generator.set("class_name", class_name);
  386. ScopeGuard function_guard { [&] {
  387. function_impl_generator.append("}\n"sv);
  388. implementation_file_generator.append(function_impl_generator.as_string_view().bytes());
  389. } };
  390. function_impl_generator.set("function_name", function_name);
  391. function_impl_generator.set("function_parameters", function_parameters.string_view());
  392. function_impl_generator.set("function_return_type", to_cpp_type(*function.return_type, interface));
  393. function_impl_generator.append(R"~~~(
  394. @function_return_type@ @class_name@::@function_name@(@function_parameters@)
  395. {
  396. m_context->make_current();
  397. )~~~");
  398. if (gl_function_modifies_framebuffer(function.name)) {
  399. function_impl_generator.append(" m_context->notify_content_will_change();\n"sv);
  400. }
  401. if (function.name == "createBuffer"sv) {
  402. function_impl_generator.append(R"~~~(
  403. GLuint handle = 0;
  404. glGenBuffers(1, &handle);
  405. return WebGLBuffer::create(m_realm, handle);
  406. )~~~");
  407. continue;
  408. }
  409. if (function.name == "createTexture"sv) {
  410. function_impl_generator.append(R"~~~(
  411. GLuint handle = 0;
  412. glGenTextures(1, &handle);
  413. return WebGLTexture::create(m_realm, handle);
  414. )~~~");
  415. continue;
  416. }
  417. if (function.name == "createFramebuffer"sv) {
  418. function_impl_generator.append(R"~~~(
  419. GLuint handle = 0;
  420. glGenFramebuffers(1, &handle);
  421. return WebGLFramebuffer::create(m_realm, handle);
  422. )~~~");
  423. continue;
  424. }
  425. if (function.name == "createRenderbuffer"sv) {
  426. function_impl_generator.append(R"~~~(
  427. GLuint handle = 0;
  428. glGenRenderbuffers(1, &handle);
  429. return WebGLRenderbuffer::create(m_realm, handle);
  430. )~~~");
  431. continue;
  432. }
  433. if (function.name == "shaderSource"sv) {
  434. function_impl_generator.append(R"~~~(
  435. Vector<GLchar*> strings;
  436. auto string = null_terminated_string(source);
  437. strings.append(string.data());
  438. Vector<GLint> length;
  439. length.append(source.bytes().size());
  440. glShaderSource(shader->handle(), 1, strings.data(), length.data());
  441. )~~~");
  442. continue;
  443. }
  444. if (function.name == "getAttribLocation"sv) {
  445. function_impl_generator.append(R"~~~(
  446. auto name_str = null_terminated_string(name);
  447. return glGetAttribLocation(program->handle(), name_str.data());
  448. )~~~");
  449. continue;
  450. }
  451. if (function.name == "vertexAttribPointer"sv) {
  452. function_impl_generator.append(R"~~~(
  453. glVertexAttribPointer(index, size, type, normalized, stride, reinterpret_cast<void*>(offset));
  454. )~~~");
  455. continue;
  456. }
  457. if (function.name == "texImage2D"sv && function.overload_index == 0) {
  458. function_impl_generator.append(R"~~~(
  459. void const* pixels_ptr = nullptr;
  460. if (pixels) {
  461. auto const& viewed_array_buffer = pixels->viewed_array_buffer();
  462. auto const& byte_buffer = viewed_array_buffer->buffer();
  463. pixels_ptr = byte_buffer.data();
  464. }
  465. glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels_ptr);
  466. )~~~");
  467. continue;
  468. }
  469. if (function.name == "texImage2D"sv && function.overload_index == 1) {
  470. // FIXME: If this function is called with an ImageData whose data attribute has been neutered,
  471. // an INVALID_VALUE error is generated.
  472. // FIXME: If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE
  473. // error is generated.
  474. // FIXME: If this function is called with an HTMLImageElement or HTMLVideoElement whose origin
  475. // differs from the origin of the containing Document, or with an HTMLCanvasElement,
  476. // ImageBitmap or OffscreenCanvas whose bitmap's origin-clean flag is set to false,
  477. // a SECURITY_ERR exception must be thrown. See Origin Restrictions.
  478. // FIXME: If source is null then an INVALID_VALUE error is generated.
  479. function_impl_generator.append(R"~~~(
  480. auto bitmap = source.visit(
  481. [](GC::Root<HTMLImageElement> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  482. return source->immutable_bitmap();
  483. },
  484. [](GC::Root<HTMLCanvasElement> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  485. auto surface = source->surface();
  486. if (!surface)
  487. return {};
  488. auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Premultiplied, surface->size()));
  489. surface->read_into_bitmap(*bitmap);
  490. return Gfx::ImmutableBitmap::create(*bitmap);
  491. },
  492. [](GC::Root<HTMLVideoElement> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  493. return Gfx::ImmutableBitmap::create(*source->bitmap());
  494. },
  495. [](GC::Root<ImageBitmap> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  496. return Gfx::ImmutableBitmap::create(*source->bitmap());
  497. },
  498. [](GC::Root<ImageData> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  499. return Gfx::ImmutableBitmap::create(source->bitmap());
  500. });
  501. if (!bitmap)
  502. return;
  503. void const* pixels_ptr = bitmap->bitmap()->begin();
  504. int width = bitmap->width();
  505. int height = bitmap->height();
  506. glTexImage2D(target, level, internalformat, width, height, 0, format, type, pixels_ptr);
  507. )~~~");
  508. continue;
  509. }
  510. if (function.name == "texSubImage2D"sv && function.overload_index == 0) {
  511. function_impl_generator.append(R"~~~(
  512. void const* pixels_ptr = nullptr;
  513. if (pixels) {
  514. auto const& viewed_array_buffer = pixels->viewed_array_buffer();
  515. auto const& byte_buffer = viewed_array_buffer->buffer();
  516. pixels_ptr = byte_buffer.data();
  517. }
  518. glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels_ptr);
  519. )~~~");
  520. continue;
  521. }
  522. if (function.name == "getShaderParameter"sv) {
  523. function_impl_generator.append(R"~~~(
  524. GLint result = 0;
  525. glGetShaderiv(shader->handle(), pname, &result);
  526. return JS::Value(result);
  527. )~~~");
  528. continue;
  529. }
  530. if (function.name == "getProgramParameter"sv) {
  531. function_impl_generator.append(R"~~~(
  532. GLint result = 0;
  533. glGetProgramiv(program->handle(), pname, &result);
  534. return JS::Value(result);
  535. )~~~");
  536. continue;
  537. }
  538. if (function.name == "bufferData"sv && function.overload_index == 0) {
  539. function_impl_generator.append(R"~~~(
  540. glBufferData(target, size, 0, usage);
  541. )~~~");
  542. continue;
  543. }
  544. if (function.name == "getUniformLocation"sv) {
  545. function_impl_generator.append(R"~~~(
  546. auto name_str = null_terminated_string(name);
  547. return WebGLUniformLocation::create(m_realm, glGetUniformLocation(program->handle(), name_str.data()));
  548. )~~~");
  549. continue;
  550. }
  551. if (function.name == "drawElements"sv) {
  552. function_impl_generator.append(R"~~~(
  553. glDrawElements(mode, count, type, reinterpret_cast<void*>(offset));
  554. needs_to_present();
  555. )~~~");
  556. continue;
  557. }
  558. if (function.name.starts_with("uniformMatrix"sv)) {
  559. auto number_of_matrix_elements = function.name.substring_view(13, 1);
  560. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  561. function_impl_generator.append(R"~~~(
  562. auto matrix_size = @number_of_matrix_elements@ * @number_of_matrix_elements@;
  563. if (value.has<Vector<float>>()) {
  564. auto& data = value.get<Vector<float>>();
  565. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), data.size() / matrix_size, transpose, data.data());
  566. return;
  567. }
  568. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*value.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  569. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  570. float const* data = float32_array.data().data();
  571. auto count = float32_array.array_length().length() / matrix_size;
  572. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), count, transpose, data);
  573. )~~~");
  574. continue;
  575. }
  576. if (function.name == "uniform1fv"sv || function.name == "uniform2fv"sv || function.name == "uniform3fv"sv || function.name == "uniform4fv"sv) {
  577. auto number_of_matrix_elements = function.name.substring_view(7, 1);
  578. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  579. function_impl_generator.append(R"~~~(
  580. if (v.has<Vector<float>>()) {
  581. auto& data = v.get<Vector<float>>();
  582. glUniform@number_of_matrix_elements@fv(location->handle(), data.size() / @number_of_matrix_elements@, data.data());
  583. return;
  584. }
  585. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*v.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  586. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  587. float const* data = float32_array.data().data();
  588. auto count = float32_array.array_length().length() / @number_of_matrix_elements@;
  589. glUniform@number_of_matrix_elements@fv(location->handle(), count, data);
  590. )~~~");
  591. continue;
  592. }
  593. if (function.name == "uniform1iv"sv || function.name == "uniform2iv"sv || function.name == "uniform3iv"sv || function.name == "uniform4iv"sv) {
  594. auto number_of_matrix_elements = function.name.substring_view(7, 1);
  595. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  596. function_impl_generator.append(R"~~~(
  597. if (v.has<Vector<int>>()) {
  598. auto& data = v.get<Vector<int>>();
  599. glUniform@number_of_matrix_elements@iv(location->handle(), data.size() / @number_of_matrix_elements@, data.data());
  600. return;
  601. }
  602. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*v.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  603. auto& int32_array = verify_cast<JS::Int32Array>(typed_array_base);
  604. int const* data = int32_array.data().data();
  605. auto count = int32_array.array_length().length() / @number_of_matrix_elements@;
  606. glUniform@number_of_matrix_elements@iv(location->handle(), count, data);
  607. )~~~");
  608. continue;
  609. }
  610. if (function.name == "getParameter"sv) {
  611. generate_get_parameter(function_impl_generator);
  612. continue;
  613. }
  614. if (function.name == "getBufferParameter"sv) {
  615. generate_get_buffer_parameter(function_impl_generator);
  616. continue;
  617. }
  618. if (function.name == "getActiveUniform"sv) {
  619. function_impl_generator.append(R"~~~(
  620. GLint size = 0;
  621. GLenum type = 0;
  622. GLsizei buf_size = 256;
  623. GLsizei length = 0;
  624. GLchar name[256];
  625. glGetActiveUniform(program->handle(), index, buf_size, &length, &size, &type, name);
  626. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  627. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  628. )~~~");
  629. continue;
  630. }
  631. if (function.name == "getActiveAttrib"sv) {
  632. function_impl_generator.append(R"~~~(
  633. GLint size = 0;
  634. GLenum type = 0;
  635. GLsizei buf_size = 256;
  636. GLsizei length = 0;
  637. GLchar name[256];
  638. glGetActiveAttrib(program->handle(), index, buf_size, &length, &size, &type, name);
  639. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  640. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  641. )~~~");
  642. continue;
  643. }
  644. if (function.name == "getShaderInfoLog"sv) {
  645. function_impl_generator.append(R"~~~(
  646. GLint info_log_length = 0;
  647. glGetShaderiv(shader->handle(), GL_INFO_LOG_LENGTH, &info_log_length);
  648. Vector<GLchar> info_log;
  649. info_log.resize(info_log_length);
  650. if (!info_log_length)
  651. return String {};
  652. glGetShaderInfoLog(shader->handle(), info_log_length, nullptr, info_log.data());
  653. return String::from_utf8_without_validation(ReadonlyBytes { info_log.data(), static_cast<size_t>(info_log_length - 1) });
  654. )~~~");
  655. continue;
  656. }
  657. if (function.name == "getProgramInfoLog"sv) {
  658. function_impl_generator.append(R"~~~(
  659. GLint info_log_length = 0;
  660. glGetProgramiv(program->handle(), GL_INFO_LOG_LENGTH, &info_log_length);
  661. Vector<GLchar> info_log;
  662. info_log.resize(info_log_length);
  663. if (!info_log_length)
  664. return String {};
  665. glGetProgramInfoLog(program->handle(), info_log_length, nullptr, info_log.data());
  666. return String::from_utf8_without_validation(ReadonlyBytes { info_log.data(), static_cast<size_t>(info_log_length - 1) });
  667. )~~~");
  668. continue;
  669. }
  670. if (function.name == "getShaderPrecisionFormat"sv) {
  671. function_impl_generator.append(R"~~~(
  672. GLint range[2];
  673. GLint precision;
  674. glGetShaderPrecisionFormat(shadertype, precisiontype, range, &precision);
  675. return WebGLShaderPrecisionFormat::create(m_realm, range[0], range[1], precision);
  676. )~~~");
  677. continue;
  678. }
  679. if (function.name == "deleteBuffer"sv) {
  680. function_impl_generator.append(R"~~~(
  681. auto handle = buffer ? buffer->handle() : 0;
  682. glDeleteBuffers(1, &handle);
  683. )~~~");
  684. continue;
  685. }
  686. if (function.name == "deleteFramebuffer"sv) {
  687. function_impl_generator.append(R"~~~(
  688. auto handle = framebuffer ? framebuffer->handle() : 0;
  689. glDeleteFramebuffers(1, &handle);
  690. )~~~");
  691. continue;
  692. }
  693. if (function.name == "deleteTexture"sv) {
  694. function_impl_generator.append(R"~~~(
  695. auto handle = texture ? texture->handle() : 0;
  696. glDeleteTextures(1, &handle);
  697. )~~~");
  698. continue;
  699. }
  700. Vector<ByteString> gl_call_arguments;
  701. for (size_t i = 0; i < function.parameters.size(); ++i) {
  702. auto const& parameter = function.parameters[i];
  703. if (parameter.type->is_numeric() || parameter.type->is_boolean()) {
  704. gl_call_arguments.append(parameter.name);
  705. continue;
  706. }
  707. if (parameter.type->is_string()) {
  708. function_impl_generator.set("parameter_name", parameter.name);
  709. function_impl_generator.append(R"~~~(
  710. auto @parameter_name@_null_terminated = null_terminated_string(@parameter_name@);
  711. )~~~");
  712. gl_call_arguments.append(ByteString::formatted("{}_null_terminated.data()", parameter.name));
  713. continue;
  714. }
  715. if (is_webgl_object_type(parameter.type->name())) {
  716. gl_call_arguments.append(ByteString::formatted("{} ? {}->handle() : 0", parameter.name, parameter.name));
  717. continue;
  718. }
  719. if (parameter.type->name() == "BufferSource"sv) {
  720. function_impl_generator.set("buffer_source_name", parameter.name);
  721. function_impl_generator.append(R"~~~(
  722. void const* ptr = nullptr;
  723. size_t byte_size = 0;
  724. if (@buffer_source_name@->is_typed_array_base()) {
  725. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*@buffer_source_name@->raw_object());
  726. ptr = typed_array_base.viewed_array_buffer()->buffer().data();
  727. byte_size = typed_array_base.viewed_array_buffer()->byte_length();
  728. } else if (@buffer_source_name@->is_data_view()) {
  729. auto& data_view = static_cast<JS::DataView&>(*@buffer_source_name@->raw_object());
  730. ptr = data_view.viewed_array_buffer()->buffer().data();
  731. byte_size = data_view.viewed_array_buffer()->byte_length();
  732. } else if (@buffer_source_name@->is_array_buffer()) {
  733. auto& array_buffer = static_cast<JS::ArrayBuffer&>(*@buffer_source_name@->raw_object());
  734. ptr = array_buffer.buffer().data();
  735. byte_size = array_buffer.byte_length();
  736. } else {
  737. VERIFY_NOT_REACHED();
  738. }
  739. )~~~");
  740. gl_call_arguments.append(ByteString::formatted("byte_size"));
  741. gl_call_arguments.append(ByteString::formatted("ptr"));
  742. continue;
  743. }
  744. VERIFY_NOT_REACHED();
  745. }
  746. StringBuilder gl_call_arguments_string_builder;
  747. gl_call_arguments_string_builder.join(", "sv, gl_call_arguments);
  748. auto gl_call_string = ByteString::formatted("{}({})", idl_to_gl_function_name(function.name), gl_call_arguments_string_builder.string_view());
  749. function_impl_generator.set("call_string", gl_call_string);
  750. if (gl_function_modifies_framebuffer(function.name)) {
  751. function_impl_generator.append(" needs_to_present();\n"sv);
  752. }
  753. if (function.return_type->name() == "undefined"sv) {
  754. function_impl_generator.append(" @call_string@;"sv);
  755. } else if (function.return_type->is_integer() || function.return_type->is_boolean()) {
  756. function_impl_generator.append(" return @call_string@;"sv);
  757. } else if (is_webgl_object_type(function.return_type->name())) {
  758. function_impl_generator.set("return_type_name", function.return_type->name());
  759. function_impl_generator.append(" return @return_type_name@::create(m_realm, @call_string@);"sv);
  760. } else {
  761. VERIFY_NOT_REACHED();
  762. }
  763. function_impl_generator.append("\n"sv);
  764. }
  765. header_file_generator.append(R"~~~(
  766. private:
  767. GC::Ref<JS::Realm> m_realm;
  768. NonnullOwnPtr<OpenGLContext> m_context;
  769. };
  770. }
  771. )~~~");
  772. implementation_file_generator.append(R"~~~(
  773. }
  774. )~~~");
  775. MUST(generated_header_file->write_until_depleted(header_file_generator.as_string_view().bytes()));
  776. MUST(generated_implementation_file->write_until_depleted(implementation_file_generator.as_string_view().bytes()));
  777. return 0;
  778. }