methods.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. import os
  2. from compat import iteritems
  3. def add_source_files(self, sources, filetype, lib_env=None, shared=False):
  4. import glob
  5. import string
  6. # if not lib_objects:
  7. if not lib_env:
  8. lib_env = self
  9. if type(filetype) == type(""):
  10. dir = self.Dir('.').abspath
  11. list = glob.glob(dir + "/" + filetype)
  12. for f in list:
  13. sources.append(self.Object(f))
  14. else:
  15. for f in filetype:
  16. sources.append(self.Object(f))
  17. class LegacyGLHeaderStruct:
  18. def __init__(self):
  19. self.vertex_lines = []
  20. self.fragment_lines = []
  21. self.uniforms = []
  22. self.attributes = []
  23. self.feedbacks = []
  24. self.fbos = []
  25. self.conditionals = []
  26. self.enums = {}
  27. self.texunits = []
  28. self.texunit_names = []
  29. self.ubos = []
  30. self.ubo_names = []
  31. self.vertex_included_files = []
  32. self.fragment_included_files = []
  33. self.reading = ""
  34. self.line_offset = 0
  35. self.vertex_offset = 0
  36. self.fragment_offset = 0
  37. def include_file_in_legacygl_header(filename, header_data, depth):
  38. fs = open(filename, "r")
  39. line = fs.readline()
  40. while(line):
  41. if (line.find("[vertex]") != -1):
  42. header_data.reading = "vertex"
  43. line = fs.readline()
  44. header_data.line_offset += 1
  45. header_data.vertex_offset = header_data.line_offset
  46. continue
  47. if (line.find("[fragment]") != -1):
  48. header_data.reading = "fragment"
  49. line = fs.readline()
  50. header_data.line_offset += 1
  51. header_data.fragment_offset = header_data.line_offset
  52. continue
  53. while(line.find("#include ") != -1):
  54. includeline = line.replace("#include ", "").strip()[1:-1]
  55. import os.path
  56. included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline)
  57. if (not included_file in header_data.vertex_included_files and header_data.reading == "vertex"):
  58. header_data.vertex_included_files += [included_file]
  59. if(include_file_in_legacygl_header(included_file, header_data, depth + 1) == None):
  60. print("Error in file '" + filename + "': #include " + includeline + "could not be found!")
  61. elif (not included_file in header_data.fragment_included_files and header_data.reading == "fragment"):
  62. header_data.fragment_included_files += [included_file]
  63. if(include_file_in_legacygl_header(included_file, header_data, depth + 1) == None):
  64. print("Error in file '" + filename + "': #include " + includeline + "could not be found!")
  65. line = fs.readline()
  66. if (line.find("#ifdef ") != -1 or line.find("#elif defined(") != -1):
  67. if (line.find("#ifdef ") != -1):
  68. ifdefline = line.replace("#ifdef ", "").strip()
  69. else:
  70. ifdefline = line.replace("#elif defined(", "").strip()
  71. ifdefline = ifdefline.replace(")", "").strip()
  72. if (line.find("_EN_") != -1):
  73. enumbase = ifdefline[:ifdefline.find("_EN_")]
  74. ifdefline = ifdefline.replace("_EN_", "_")
  75. line = line.replace("_EN_", "_")
  76. # print(enumbase+":"+ifdefline);
  77. if (enumbase not in header_data.enums):
  78. header_data.enums[enumbase] = []
  79. if (ifdefline not in header_data.enums[enumbase]):
  80. header_data.enums[enumbase].append(ifdefline)
  81. elif (not ifdefline in header_data.conditionals):
  82. header_data.conditionals += [ifdefline]
  83. if (line.find("uniform") != -1 and line.lower().find("texunit:") != -1):
  84. # texture unit
  85. texunitstr = line[line.find(":") + 1:].strip()
  86. if (texunitstr == "auto"):
  87. texunit = "-1"
  88. else:
  89. texunit = str(int(texunitstr))
  90. uline = line[:line.lower().find("//")]
  91. uline = uline.replace("uniform", "")
  92. uline = uline.replace("highp", "")
  93. uline = uline.replace(";", "")
  94. lines = uline.split(",")
  95. for x in lines:
  96. x = x.strip()
  97. x = x[x.rfind(" ") + 1:]
  98. if (x.find("[") != -1):
  99. # unfiorm array
  100. x = x[:x.find("[")]
  101. if (not x in header_data.texunit_names):
  102. header_data.texunits += [(x, texunit)]
  103. header_data.texunit_names += [x]
  104. elif (line.find("uniform") != -1 and line.lower().find("ubo:") != -1):
  105. # uniform buffer object
  106. ubostr = line[line.find(":") + 1:].strip()
  107. ubo = str(int(ubostr))
  108. uline = line[:line.lower().find("//")]
  109. uline = uline[uline.find("uniform") + len("uniform"):]
  110. uline = uline.replace("highp", "")
  111. uline = uline.replace(";", "")
  112. uline = uline.replace("{", "").strip()
  113. lines = uline.split(",")
  114. for x in lines:
  115. x = x.strip()
  116. x = x[x.rfind(" ") + 1:]
  117. if (x.find("[") != -1):
  118. # unfiorm array
  119. x = x[:x.find("[")]
  120. if (not x in header_data.ubo_names):
  121. header_data.ubos += [(x, ubo)]
  122. header_data.ubo_names += [x]
  123. elif (line.find("uniform") != -1 and line.find("{") == -1 and line.find(";") != -1):
  124. uline = line.replace("uniform", "")
  125. uline = uline.replace(";", "")
  126. lines = uline.split(",")
  127. for x in lines:
  128. x = x.strip()
  129. x = x[x.rfind(" ") + 1:]
  130. if (x.find("[") != -1):
  131. # unfiorm array
  132. x = x[:x.find("[")]
  133. if (not x in header_data.uniforms):
  134. header_data.uniforms += [x]
  135. if (line.strip().find("attribute ") == 0 and line.find("attrib:") != -1):
  136. uline = line.replace("in ", "")
  137. uline = uline.replace("attribute ", "")
  138. uline = uline.replace("highp ", "")
  139. uline = uline.replace(";", "")
  140. uline = uline[uline.find(" "):].strip()
  141. if (uline.find("//") != -1):
  142. name, bind = uline.split("//")
  143. if (bind.find("attrib:") != -1):
  144. name = name.strip()
  145. bind = bind.replace("attrib:", "").strip()
  146. header_data.attributes += [(name, bind)]
  147. if (line.strip().find("out ") == 0 and line.find("tfb:") != -1):
  148. uline = line.replace("out ", "")
  149. uline = uline.replace("highp ", "")
  150. uline = uline.replace(";", "")
  151. uline = uline[uline.find(" "):].strip()
  152. if (uline.find("//") != -1):
  153. name, bind = uline.split("//")
  154. if (bind.find("tfb:") != -1):
  155. name = name.strip()
  156. bind = bind.replace("tfb:", "").strip()
  157. header_data.feedbacks += [(name, bind)]
  158. line = line.replace("\r", "")
  159. line = line.replace("\n", "")
  160. # line=line.replace("\\","\\\\")
  161. # line=line.replace("\"","\\\"")
  162. # line=line+"\\n\\"
  163. if (header_data.reading == "vertex"):
  164. header_data.vertex_lines += [line]
  165. if (header_data.reading == "fragment"):
  166. header_data.fragment_lines += [line]
  167. line = fs.readline()
  168. header_data.line_offset += 1
  169. fs.close()
  170. return header_data
  171. def build_legacygl_header(filename, include, class_suffix, output_attribs, gles2=False):
  172. header_data = LegacyGLHeaderStruct()
  173. include_file_in_legacygl_header(filename, header_data, 0)
  174. out_file = filename + ".gen.h"
  175. fd = open(out_file, "w")
  176. enum_constants = []
  177. fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
  178. out_file_base = out_file
  179. out_file_base = out_file_base[out_file_base.rfind("/") + 1:]
  180. out_file_base = out_file_base[out_file_base.rfind("\\") + 1:]
  181. # print("out file "+out_file+" base " +out_file_base)
  182. out_file_ifdef = out_file_base.replace(".", "_").upper()
  183. fd.write("#ifndef " + out_file_ifdef + class_suffix + "_120\n")
  184. fd.write("#define " + out_file_ifdef + class_suffix + "_120\n")
  185. out_file_class = out_file_base.replace(".glsl.gen.h", "").title().replace("_", "").replace(".", "") + "Shader" + class_suffix
  186. fd.write("\n\n")
  187. fd.write("#include \"" + include + "\"\n\n\n")
  188. fd.write("class " + out_file_class + " : public Shader" + class_suffix + " {\n\n")
  189. fd.write("\t virtual String get_shader_name() const { return \"" + out_file_class + "\"; }\n")
  190. fd.write("public:\n\n")
  191. if (len(header_data.conditionals)):
  192. fd.write("\tenum Conditionals {\n")
  193. for x in header_data.conditionals:
  194. fd.write("\t\t" + x.upper() + ",\n")
  195. fd.write("\t};\n\n")
  196. if (len(header_data.uniforms)):
  197. fd.write("\tenum Uniforms {\n")
  198. for x in header_data.uniforms:
  199. fd.write("\t\t" + x.upper() + ",\n")
  200. fd.write("\t};\n\n")
  201. fd.write("\t_FORCE_INLINE_ int get_uniform(Uniforms p_uniform) const { return _get_uniform(p_uniform); }\n\n")
  202. if (len(header_data.conditionals)):
  203. fd.write("\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\n\n")
  204. fd.write("\t#define _FU if (get_uniform(p_uniform)<0) return; ERR_FAIL_COND( get_active()!=this );\n\n ")
  205. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  206. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  207. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  208. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  209. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  210. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  211. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  212. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  213. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  214. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  215. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, unsigned long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  216. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  217. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Color& p_color) { _FU GLfloat col[4]={p_color.r,p_color.g,p_color.b,p_color.a}; glUniform4fv(get_uniform(p_uniform),1,col); }\n\n")
  218. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector2& p_vec2) { _FU GLfloat vec2[2]={p_vec2.x,p_vec2.y}; glUniform2fv(get_uniform(p_uniform),1,vec2); }\n\n")
  219. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector3& p_vec3) { _FU GLfloat vec3[3]={p_vec3.x,p_vec3.y,p_vec3.z}; glUniform3fv(get_uniform(p_uniform),1,vec3); }\n\n")
  220. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b) { _FU glUniform2f(get_uniform(p_uniform),p_a,p_b); }\n\n")
  221. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c) { _FU glUniform3f(get_uniform(p_uniform),p_a,p_b,p_c); }\n\n")
  222. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c, float p_d) { _FU glUniform4f(get_uniform(p_uniform),p_a,p_b,p_c,p_d); }\n\n")
  223. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU
  224. const Transform &tr = p_transform;
  225. GLfloat matrix[16]={ /* build a 16x16 matrix */
  226. tr.basis.elements[0][0],
  227. tr.basis.elements[1][0],
  228. tr.basis.elements[2][0],
  229. 0,
  230. tr.basis.elements[0][1],
  231. tr.basis.elements[1][1],
  232. tr.basis.elements[2][1],
  233. 0,
  234. tr.basis.elements[0][2],
  235. tr.basis.elements[1][2],
  236. tr.basis.elements[2][2],
  237. 0,
  238. tr.origin.x,
  239. tr.origin.y,
  240. tr.origin.z,
  241. 1
  242. };
  243. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  244. }
  245. """)
  246. fd.write("""_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform2D& p_transform) { _FU
  247. const Transform2D &tr = p_transform;
  248. GLfloat matrix[16]={ /* build a 16x16 matrix */
  249. tr.elements[0][0],
  250. tr.elements[0][1],
  251. 0,
  252. 0,
  253. tr.elements[1][0],
  254. tr.elements[1][1],
  255. 0,
  256. 0,
  257. 0,
  258. 0,
  259. 1,
  260. 0,
  261. tr.elements[2][0],
  262. tr.elements[2][1],
  263. 0,
  264. 1
  265. };
  266. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  267. }
  268. """)
  269. fd.write("""_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU
  270. GLfloat matrix[16];
  271. for (int i=0;i<4;i++) {
  272. for (int j=0;j<4;j++) {
  273. matrix[i*4+j]=p_matrix.matrix[i][j];
  274. }
  275. }
  276. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  277. } """)
  278. fd.write("\n\n#undef _FU\n\n\n")
  279. fd.write("\tvirtual void init() {\n\n")
  280. enum_value_count = 0
  281. if (len(header_data.enums)):
  282. fd.write("\t\t//Written using math, given nonstandarity of 64 bits integer constants..\n")
  283. fd.write("\t\tstatic const Enum _enums[]={\n")
  284. bitofs = len(header_data.conditionals)
  285. enum_vals = []
  286. for xv in header_data.enums:
  287. x = header_data.enums[xv]
  288. bits = 1
  289. amt = len(x)
  290. # print(x)
  291. while(2**bits < amt):
  292. bits += 1
  293. # print("amount: "+str(amt)+" bits "+str(bits));
  294. strs = "{"
  295. for i in range(amt):
  296. strs += "\"#define " + x[i] + "\\n\","
  297. v = {}
  298. v["set_mask"] = "uint64_t(" + str(i) + ")<<" + str(bitofs)
  299. v["clear_mask"] = "((uint64_t(1)<<40)-1) ^ (((uint64_t(1)<<" + str(bits) + ") - 1)<<" + str(bitofs) + ")"
  300. enum_vals.append(v)
  301. enum_constants.append(x[i])
  302. strs += "NULL}"
  303. fd.write("\t\t\t{(uint64_t(1<<" + str(bits) + ")-1)<<" + str(bitofs) + "," + str(bitofs) + "," + strs + "},\n")
  304. bitofs += bits
  305. fd.write("\t\t};\n\n")
  306. fd.write("\t\tstatic const EnumValue _enum_values[]={\n")
  307. enum_value_count = len(enum_vals)
  308. for x in enum_vals:
  309. fd.write("\t\t\t{" + x["set_mask"] + "," + x["clear_mask"] + "},\n")
  310. fd.write("\t\t};\n\n")
  311. conditionals_found = []
  312. if (len(header_data.conditionals)):
  313. fd.write("\t\tstatic const char* _conditional_strings[]={\n")
  314. if (len(header_data.conditionals)):
  315. for x in header_data.conditionals:
  316. fd.write("\t\t\t\"#define " + x + "\\n\",\n")
  317. conditionals_found.append(x)
  318. fd.write("\t\t};\n\n")
  319. else:
  320. fd.write("\t\tstatic const char **_conditional_strings=NULL;\n")
  321. if (len(header_data.uniforms)):
  322. fd.write("\t\tstatic const char* _uniform_strings[]={\n")
  323. if (len(header_data.uniforms)):
  324. for x in header_data.uniforms:
  325. fd.write("\t\t\t\"" + x + "\",\n")
  326. fd.write("\t\t};\n\n")
  327. else:
  328. fd.write("\t\tstatic const char **_uniform_strings=NULL;\n")
  329. if output_attribs:
  330. if (len(header_data.attributes)):
  331. fd.write("\t\tstatic AttributePair _attribute_pairs[]={\n")
  332. for x in header_data.attributes:
  333. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  334. fd.write("\t\t};\n\n")
  335. else:
  336. fd.write("\t\tstatic AttributePair *_attribute_pairs=NULL;\n")
  337. feedback_count = 0
  338. if (not gles2 and len(header_data.feedbacks)):
  339. fd.write("\t\tstatic const Feedback _feedbacks[]={\n")
  340. for x in header_data.feedbacks:
  341. name = x[0]
  342. cond = x[1]
  343. if (cond in conditionals_found):
  344. fd.write("\t\t\t{\"" + name + "\"," + str(conditionals_found.index(cond)) + "},\n")
  345. else:
  346. fd.write("\t\t\t{\"" + name + "\",-1},\n")
  347. feedback_count += 1
  348. fd.write("\t\t};\n\n")
  349. else:
  350. if gles2:
  351. pass
  352. else:
  353. fd.write("\t\tstatic const Feedback* _feedbacks=NULL;\n")
  354. if (len(header_data.texunits)):
  355. fd.write("\t\tstatic TexUnitPair _texunit_pairs[]={\n")
  356. for x in header_data.texunits:
  357. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  358. fd.write("\t\t};\n\n")
  359. else:
  360. fd.write("\t\tstatic TexUnitPair *_texunit_pairs=NULL;\n")
  361. if (not gles2 and len(header_data.ubos)):
  362. fd.write("\t\tstatic UBOPair _ubo_pairs[]={\n")
  363. for x in header_data.ubos:
  364. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  365. fd.write("\t\t};\n\n")
  366. else:
  367. if gles2:
  368. pass
  369. else:
  370. fd.write("\t\tstatic UBOPair *_ubo_pairs=NULL;\n")
  371. fd.write("\t\tstatic const char _vertex_code[]={\n")
  372. for x in header_data.vertex_lines:
  373. for i in range(len(x)):
  374. fd.write(str(ord(x[i])) + ",")
  375. fd.write(str(ord('\n')) + ",")
  376. fd.write("\t\t0};\n\n")
  377. fd.write("\t\tstatic const int _vertex_code_start=" + str(header_data.vertex_offset) + ";\n")
  378. fd.write("\t\tstatic const char _fragment_code[]={\n")
  379. for x in header_data.fragment_lines:
  380. for i in range(len(x)):
  381. fd.write(str(ord(x[i])) + ",")
  382. fd.write(str(ord('\n')) + ",")
  383. fd.write("\t\t0};\n\n")
  384. fd.write("\t\tstatic const int _fragment_code_start=" + str(header_data.fragment_offset) + ";\n")
  385. if output_attribs:
  386. if gles2:
  387. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_attribute_pairs," + str(len(header_data.attributes)) + ", _texunit_pairs," + str(len(header_data.texunits)) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  388. else:
  389. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_attribute_pairs," + str(len(header_data.attributes)) + ", _texunit_pairs," + str(len(header_data.texunits)) + ",_ubo_pairs," + str(len(header_data.ubos)) + ",_feedbacks," + str(feedback_count) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  390. else:
  391. if gles2:
  392. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_texunit_pairs," + str(len(header_data.texunits)) + ",_enums," + str(len(header_data.enums)) + ",_enum_values," + str(enum_value_count) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  393. else:
  394. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_texunit_pairs," + str(len(header_data.texunits)) + ",_enums," + str(len(header_data.enums)) + ",_enum_values," + str(enum_value_count) + ",_ubo_pairs," + str(len(header_data.ubos)) + ",_feedbacks," + str(feedback_count) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  395. fd.write("\t}\n\n")
  396. if (len(enum_constants)):
  397. fd.write("\tenum EnumConditionals {\n")
  398. for x in enum_constants:
  399. fd.write("\t\t" + x.upper() + ",\n")
  400. fd.write("\t};\n\n")
  401. fd.write("\tvoid set_enum_conditional(EnumConditionals p_cond) { _set_enum_conditional(p_cond); }\n")
  402. fd.write("};\n\n")
  403. fd.write("#endif\n\n")
  404. fd.close()
  405. def build_gles3_headers(target, source, env):
  406. for x in source:
  407. build_legacygl_header(str(x), include="drivers/gles3/shader_gles3.h", class_suffix="GLES3", output_attribs=True)
  408. def build_gles2_headers(target, source, env):
  409. for x in source:
  410. build_legacygl_header(str(x), include="drivers/gles2/shader_gles2.h", class_suffix="GLES2", output_attribs=True, gles2=True)
  411. def add_module_version_string(self,s):
  412. self.module_version_string += "." + s
  413. def update_version(module_version_string=""):
  414. build_name = "custom_build"
  415. if (os.getenv("BUILD_NAME") != None):
  416. build_name = os.getenv("BUILD_NAME")
  417. print("Using custom build name: " + build_name)
  418. import version
  419. f = open("core/version_generated.gen.h", "w")
  420. f.write("#define VERSION_SHORT_NAME \"" + str(version.short_name) + "\"\n")
  421. f.write("#define VERSION_NAME \"" + str(version.name) + "\"\n")
  422. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  423. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  424. if (hasattr(version, 'patch')):
  425. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  426. f.write("#define VERSION_STATUS \"" + str(version.status) + "\"\n")
  427. f.write("#define VERSION_BUILD \"" + str(build_name) + "\"\n")
  428. f.write("#define VERSION_MODULE_CONFIG \"" + str(version.module_config) + module_version_string + "\"\n")
  429. import datetime
  430. f.write("#define VERSION_YEAR " + str(datetime.datetime.now().year) + "\n")
  431. f.close()
  432. fhash = open("core/version_hash.gen.h", "w")
  433. githash = ""
  434. if os.path.isfile(".git/HEAD"):
  435. head = open(".git/HEAD", "r").readline().strip()
  436. if head.startswith("ref: "):
  437. head = ".git/" + head[5:]
  438. if os.path.isfile(head):
  439. githash = open(head, "r").readline().strip()
  440. else:
  441. githash = head
  442. fhash.write("#define VERSION_HASH \"" + githash + "\"")
  443. fhash.close()
  444. def parse_cg_file(fname, uniforms, sizes, conditionals):
  445. import re
  446. fs = open(fname, "r")
  447. line = fs.readline()
  448. while line:
  449. if re.match(r"^\s*uniform", line):
  450. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  451. type = res.groups(1)
  452. name = res.groups(2)
  453. uniforms.append(name)
  454. if (type.find("texobj") != -1):
  455. sizes.append(1)
  456. else:
  457. t = re.match(r"float(\d)x(\d)", type)
  458. if t:
  459. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  460. else:
  461. t = re.match(r"float(\d)", type)
  462. sizes.append(int(t.groups(1)))
  463. if line.find("[branch]") != -1:
  464. conditionals.append(name)
  465. line = fs.readline()
  466. fs.close()
  467. import glob
  468. def detect_modules():
  469. module_list = []
  470. includes_cpp = ""
  471. register_cpp = ""
  472. unregister_cpp = ""
  473. files = glob.glob("modules/*")
  474. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  475. for x in files:
  476. if (not os.path.isdir(x)):
  477. continue
  478. if (not os.path.exists(x + "/config.py")):
  479. continue
  480. x = x.replace("modules/", "") # rest of world
  481. x = x.replace("modules\\", "") # win32
  482. module_list.append(x)
  483. try:
  484. with open("modules/" + x + "/register_types.h"):
  485. includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
  486. register_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  487. register_cpp += '\tregister_' + x + '_types();\n'
  488. register_cpp += '#endif\n'
  489. unregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  490. unregister_cpp += '\tunregister_' + x + '_types();\n'
  491. unregister_cpp += '#endif\n'
  492. except IOError:
  493. pass
  494. modules_cpp = """
  495. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  496. #include "register_module_types.h"
  497. """ + includes_cpp + """
  498. void register_module_types() {
  499. """ + register_cpp + """
  500. }
  501. void unregister_module_types() {
  502. """ + unregister_cpp + """
  503. }
  504. """
  505. with open("modules/register_module_types.gen.cpp", "w") as f:
  506. f.write(modules_cpp)
  507. return module_list
  508. def win32_spawn(sh, escape, cmd, args, env):
  509. import subprocess
  510. newargs = ' '.join(args[1:])
  511. cmdline = cmd + " " + newargs
  512. startupinfo = subprocess.STARTUPINFO()
  513. #startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  514. for e in env:
  515. if type(env[e]) != type(""):
  516. env[e] = str(env[e])
  517. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  518. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  519. data, err = proc.communicate()
  520. rv = proc.wait()
  521. if rv:
  522. print("=====")
  523. print(err)
  524. print("=====")
  525. return rv
  526. """
  527. def win32_spawn(sh, escape, cmd, args, spawnenv):
  528. import win32file
  529. import win32event
  530. import win32process
  531. import win32security
  532. for var in spawnenv:
  533. spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
  534. sAttrs = win32security.SECURITY_ATTRIBUTES()
  535. StartupInfo = win32process.STARTUPINFO()
  536. newargs = ' '.join(map(escape, args[1:]))
  537. cmdline = cmd + " " + newargs
  538. # check for any special operating system commands
  539. if cmd == 'del':
  540. for arg in args[1:]:
  541. win32file.DeleteFile(arg)
  542. exit_code = 0
  543. else:
  544. # otherwise execute the command.
  545. hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
  546. win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
  547. exit_code = win32process.GetExitCodeProcess(hProcess)
  548. win32file.CloseHandle(hProcess);
  549. win32file.CloseHandle(hThread);
  550. return exit_code
  551. """
  552. def android_add_flat_dir(self, dir):
  553. if (dir not in self.android_flat_dirs):
  554. self.android_flat_dirs.append(dir)
  555. def android_add_maven_repository(self, url):
  556. if (url not in self.android_maven_repos):
  557. self.android_maven_repos.append(url)
  558. def android_add_dependency(self, depline):
  559. if (depline not in self.android_dependencies):
  560. self.android_dependencies.append(depline)
  561. def android_add_java_dir(self, subpath):
  562. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  563. if (base_path not in self.android_java_dirs):
  564. self.android_java_dirs.append(base_path)
  565. def android_add_res_dir(self, subpath):
  566. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  567. if (base_path not in self.android_res_dirs):
  568. self.android_res_dirs.append(base_path)
  569. def android_add_aidl_dir(self, subpath):
  570. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  571. if (base_path not in self.android_aidl_dirs):
  572. self.android_aidl_dirs.append(base_path)
  573. def android_add_jni_dir(self, subpath):
  574. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  575. if (base_path not in self.android_jni_dirs):
  576. self.android_jni_dirs.append(base_path)
  577. def android_add_gradle_plugin(self, plugin):
  578. if (plugin not in self.android_gradle_plugins):
  579. self.android_gradle_plugins.append(plugin)
  580. def android_add_gradle_classpath(self, classpath):
  581. if (classpath not in self.android_gradle_classpath):
  582. self.android_gradle_classpath.append(classpath)
  583. def android_add_default_config(self, config):
  584. if (config not in self.android_default_config):
  585. self.android_default_config.append(config)
  586. def android_add_to_manifest(self, file):
  587. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  588. with open(base_path, "r") as f:
  589. self.android_manifest_chunk += f.read()
  590. def android_add_to_permissions(self, file):
  591. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  592. with open(base_path, "r") as f:
  593. self.android_permission_chunk += f.read()
  594. def android_add_to_attributes(self, file):
  595. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  596. with open(base_path, "r") as f:
  597. self.android_appattributes_chunk += f.read()
  598. def disable_module(self):
  599. self.disabled_modules.append(self.current_module)
  600. def use_windows_spawn_fix(self, platform=None):
  601. if (os.name != "nt"):
  602. return # not needed, only for windows
  603. # On Windows, due to the limited command line length, when creating a static library
  604. # from a very high number of objects SCons will invoke "ar" once per object file;
  605. # that makes object files with same names to be overwritten so the last wins and
  606. # the library looses symbols defined by overwritten objects.
  607. # By enabling quick append instead of the default mode (replacing), libraries will
  608. # got built correctly regardless the invocation strategy.
  609. # Furthermore, since SCons will rebuild the library from scratch when an object file
  610. # changes, no multiple versions of the same object file will be present.
  611. self.Replace(ARFLAGS='q')
  612. import subprocess
  613. def mySubProcess(cmdline, env):
  614. startupinfo = subprocess.STARTUPINFO()
  615. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  616. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  617. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  618. data, err = proc.communicate()
  619. rv = proc.wait()
  620. if rv:
  621. print("=====")
  622. print(err)
  623. print("=====")
  624. return rv
  625. def mySpawn(sh, escape, cmd, args, env):
  626. newargs = ' '.join(args[1:])
  627. cmdline = cmd + " " + newargs
  628. rv = 0
  629. env = {str(key): str(value) for key, value in iteritems(env)}
  630. if len(cmdline) > 32000 and cmd.endswith("ar"):
  631. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  632. for i in range(3, len(args)):
  633. rv = mySubProcess(cmdline + args[i], env)
  634. if rv:
  635. break
  636. else:
  637. rv = mySubProcess(cmdline, env)
  638. return rv
  639. self['SPAWN'] = mySpawn
  640. def split_lib(self, libname, src_list = None, env_lib = None):
  641. import string
  642. env = self
  643. num = 0
  644. cur_base = ""
  645. max_src = 64
  646. list = []
  647. lib_list = []
  648. if src_list == None:
  649. src_list = getattr(env, libname + "_sources")
  650. if type(env_lib) == type(None):
  651. env_lib = env
  652. for f in src_list:
  653. fname = ""
  654. if type(f) == type(""):
  655. fname = env.File(f).path
  656. else:
  657. fname = env.File(f)[0].path
  658. fname = fname.replace("\\", "/")
  659. base = string.join(fname.split("/")[:2], "/")
  660. if base != cur_base and len(list) > max_src:
  661. if num > 0:
  662. lib = env_lib.add_library(libname + str(num), list)
  663. lib_list.append(lib)
  664. list = []
  665. num = num + 1
  666. cur_base = base
  667. list.append(f)
  668. lib = env_lib.add_library(libname + str(num), list)
  669. lib_list.append(lib)
  670. if len(lib_list) > 0:
  671. import os, sys
  672. if os.name == 'posix' and sys.platform == 'msys':
  673. env.Replace(ARFLAGS=['rcsT'])
  674. lib = env_lib.add_library(libname + "_collated", lib_list)
  675. lib_list = [lib]
  676. lib_base = []
  677. env_lib.add_source_files(lib_base, "*.cpp")
  678. lib = env_lib.add_library(libname, lib_base)
  679. lib_list.insert(0, lib)
  680. env.Prepend(LIBS=lib_list)
  681. def save_active_platforms(apnames, ap):
  682. for x in ap:
  683. names = ['logo']
  684. if os.path.isfile(x + "/run_icon.png"):
  685. names.append('run_icon')
  686. for name in names:
  687. pngf = open(x + "/" + name + ".png", "rb")
  688. b = pngf.read(1)
  689. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  690. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  691. while(len(b) == 1):
  692. str += hex(ord(b))
  693. b = pngf.read(1)
  694. if (len(b) == 1):
  695. str += ","
  696. str += "};\n"
  697. pngf.close()
  698. wf = x + "/" + name + ".gen.h"
  699. with open(wf, "w") as pngw:
  700. pngw.write(str)
  701. def no_verbose(sys, env):
  702. colors = {}
  703. # Colors are disabled in non-TTY environments such as pipes. This means
  704. # that if output is redirected to a file, it will not contain color codes
  705. if sys.stdout.isatty():
  706. colors['cyan'] = '\033[96m'
  707. colors['purple'] = '\033[95m'
  708. colors['blue'] = '\033[94m'
  709. colors['green'] = '\033[92m'
  710. colors['yellow'] = '\033[93m'
  711. colors['red'] = '\033[91m'
  712. colors['end'] = '\033[0m'
  713. else:
  714. colors['cyan'] = ''
  715. colors['purple'] = ''
  716. colors['blue'] = ''
  717. colors['green'] = ''
  718. colors['yellow'] = ''
  719. colors['red'] = ''
  720. colors['end'] = ''
  721. compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  722. java_compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  723. compile_shared_source_message = '%sCompiling shared %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  724. link_program_message = '%sLinking Program %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  725. link_library_message = '%sLinking Static Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  726. ranlib_library_message = '%sRanlib Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  727. link_shared_library_message = '%sLinking Shared Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  728. java_library_message = '%sCreating Java Archive %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  729. env.Append(CXXCOMSTR=[compile_source_message])
  730. env.Append(CCCOMSTR=[compile_source_message])
  731. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  732. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  733. env.Append(ARCOMSTR=[link_library_message])
  734. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  735. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  736. env.Append(LINKCOMSTR=[link_program_message])
  737. env.Append(JARCOMSTR=[java_library_message])
  738. env.Append(JAVACCOMSTR=[java_compile_source_message])
  739. def detect_visual_c_compiler_version(tools_env):
  740. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  741. # (see the SCons documentation for more information on what it does)...
  742. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  743. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  744. # the proper vc version that will be called
  745. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  746. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  747. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  748. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  749. # the following string values:
  750. # "" Compiler not detected
  751. # "amd64" Native 64 bit compiler
  752. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  753. # "x86" Native 32 bit compiler
  754. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  755. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  756. # and similar architectures/compilers
  757. # Set chosen compiler to "not detected"
  758. vc_chosen_compiler_index = -1
  759. vc_chosen_compiler_str = ""
  760. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  761. if 'VCINSTALLDIR' in tools_env:
  762. # print("Checking VCINSTALLDIR")
  763. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  764. # First test if amd64 and amd64_x86 compilers are present in the path
  765. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  766. if(vc_amd64_compiler_detection_index > -1):
  767. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  768. vc_chosen_compiler_str = "amd64"
  769. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  770. if(vc_amd64_x86_compiler_detection_index > -1
  771. and (vc_chosen_compiler_index == -1
  772. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  773. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  774. vc_chosen_compiler_str = "amd64_x86"
  775. # Now check the 32 bit compilers
  776. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  777. if(vc_x86_compiler_detection_index > -1
  778. and (vc_chosen_compiler_index == -1
  779. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  780. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  781. vc_chosen_compiler_str = "x86"
  782. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env['VCINSTALLDIR'] + "BIN\\x86_amd64;")
  783. if(vc_x86_amd64_compiler_detection_index > -1
  784. and (vc_chosen_compiler_index == -1
  785. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  786. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  787. vc_chosen_compiler_str = "x86_amd64"
  788. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  789. if 'VCTOOLSINSTALLDIR' in tools_env:
  790. # print("Checking VCTOOLSINSTALLDIR")
  791. # Newer versions have a different path available
  792. vc_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X64;")
  793. if(vc_amd64_compiler_detection_index > -1):
  794. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  795. vc_chosen_compiler_str = "amd64"
  796. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X86;")
  797. if(vc_amd64_x86_compiler_detection_index > -1
  798. and (vc_chosen_compiler_index == -1
  799. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  800. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  801. vc_chosen_compiler_str = "amd64_x86"
  802. vc_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X86;")
  803. if(vc_x86_compiler_detection_index > -1
  804. and (vc_chosen_compiler_index == -1
  805. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  806. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  807. vc_chosen_compiler_str = "x86"
  808. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X64;")
  809. if(vc_x86_amd64_compiler_detection_index > -1
  810. and (vc_chosen_compiler_index == -1
  811. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  812. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  813. vc_chosen_compiler_str = "x86_amd64"
  814. # debug help
  815. # print(vc_amd64_compiler_detection_index)
  816. # print(vc_amd64_x86_compiler_detection_index)
  817. # print(vc_x86_compiler_detection_index)
  818. # print(vc_x86_amd64_compiler_detection_index)
  819. # print("chosen "+str(vc_chosen_compiler_index)+ " | "+str(vc_chosen_compiler_str))
  820. return vc_chosen_compiler_str
  821. def find_visual_c_batch_file(env):
  822. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  823. version = get_default_version(env)
  824. (host_platform, target_platform,req_target_platform) = get_host_target(env)
  825. return find_batch_file(env, version, host_platform, target_platform)[0]
  826. def generate_cpp_hint_file(filename):
  827. import os.path
  828. if os.path.isfile(filename):
  829. # Don't overwrite an existing hint file since the user may have customized it.
  830. pass
  831. else:
  832. try:
  833. with open(filename, "w") as fd:
  834. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  835. except IOError:
  836. print("Could not write cpp.hint file.")
  837. def generate_vs_project(env, num_jobs):
  838. batch_file = find_visual_c_batch_file(env)
  839. if batch_file:
  840. def build_commandline(commands):
  841. common_build_prefix = ['cmd /V /C set "plat=$(PlatformTarget)"',
  842. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  843. 'set "tools=yes"',
  844. '(if "$(Configuration)"=="release" (set "tools=no"))',
  845. 'call "' + batch_file + '" !plat!']
  846. result = " ^& ".join(common_build_prefix + [commands])
  847. # print("Building commandline: ", result)
  848. return result
  849. env.AddToVSProject(env.core_sources)
  850. env.AddToVSProject(env.main_sources)
  851. env.AddToVSProject(env.modules_sources)
  852. env.AddToVSProject(env.scene_sources)
  853. env.AddToVSProject(env.servers_sources)
  854. env.AddToVSProject(env.editor_sources)
  855. # windows allows us to have spaces in paths, so we need
  856. # to double quote off the directory. However, the path ends
  857. # in a backslash, so we need to remove this, lest it escape the
  858. # last double quote off, confusing MSBuild
  859. env['MSVSBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  860. env['MSVSREBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! vsproj=yes -j' + str(num_jobs))
  861. env['MSVSCLEANCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" --clean platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  862. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  863. # required for Visual Studio to understand that it needs to generate an NMAKE
  864. # project. Do not modify without knowing what you are doing.
  865. debug_variants = ['debug|Win32'] + ['debug|x64']
  866. release_variants = ['release|Win32'] + ['release|x64']
  867. release_debug_variants = ['release_debug|Win32'] + ['release_debug|x64']
  868. variants = debug_variants + release_variants + release_debug_variants
  869. debug_targets = ['bin\\godot.windows.tools.32.exe'] + ['bin\\godot.windows.tools.64.exe']
  870. release_targets = ['bin\\godot.windows.opt.32.exe'] + ['bin\\godot.windows.opt.64.exe']
  871. release_debug_targets = ['bin\\godot.windows.opt.tools.32.exe'] + ['bin\\godot.windows.opt.tools.64.exe']
  872. targets = debug_targets + release_targets + release_debug_targets
  873. msvproj = env.MSVSProject(target=['#godot' + env['MSVSPROJECTSUFFIX']],
  874. incs=env.vs_incs,
  875. srcs=env.vs_srcs,
  876. runfile=targets,
  877. buildtarget=targets,
  878. auto_build_solution=1,
  879. variant=variants)
  880. else:
  881. print("Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project.")
  882. def precious_program(env, program, sources, **args):
  883. program = env.ProgramOriginal(program, sources, **args)
  884. env.Precious(program)
  885. return program
  886. def add_shared_library(env, name, sources, **args):
  887. library = env.SharedLibrary(name, sources, **args)
  888. env.NoCache(library)
  889. return library
  890. def add_library(env, name, sources, **args):
  891. library = env.Library(name, sources, **args)
  892. env.NoCache(library)
  893. return library
  894. def add_program(env, name, sources, **args):
  895. program = env.Program(name, sources, **args)
  896. env.NoCache(program)
  897. return program