methods.py 51 KB

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