Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new feature: map generator #276

Draft
wants to merge 16 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 182 additions & 1 deletion src/api/handlers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -208,8 +209,16 @@ func RemoveSave(w http.ResponseWriter, r *http.Request) {
func CreateSaveHandler(w http.ResponseWriter, r *http.Request) {
var err error
var resp interface{}
var mapGenSettingsFileName string
var mapSettingsFileName string

defer func() {
if mapGenSettingsFileName != "" {
_ = os.Remove(mapGenSettingsFileName)
}
if mapSettingsFileName != "" {
_ = os.Remove(mapSettingsFileName)
}
WriteResponse(w, resp)
}()

Expand All @@ -222,9 +231,47 @@ func CreateSaveHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
return
}

w.Header().Set("Content-Type", "application/json;charset=UTF-8")

body, resp, err := ReadRequestBody(w, r)
if err != nil {
return
}

var mapGenSettings factorio.MapGenSettings
mapGenSettings, resp, err = UnmarshallMapGenSettingsJson(body, w)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

mapGenSettingsFileName, resp, err = ParseSettingsAsFile(mapGenSettings)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

var mapSettings factorio.MapSettings
mapSettings, resp, err = UnmarshallMapSettingsJson(body, w)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

mapSettingsFileName, resp, err = ParseSettingsAsFile(mapSettings)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

config := bootstrap.GetConfig()
saveFile := filepath.Join(config.FactorioSavesDir, saveName)
cmdOut, err := factorio.CreateSave(saveFile)
cmdOut, err := factorio.CreateSave(saveFile, mapGenSettingsFileName, mapSettingsFileName)
if err != nil {
resp = fmt.Sprintf("Error creating save {%s}: %s", saveName, err)
log.Println(resp)
Expand Down Expand Up @@ -410,6 +457,91 @@ func CheckServer(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
}

func DefaultMapSettings(w http.ResponseWriter, r *http.Request) {
WriteResponse(w, factorio.DefaultMapSettings())
}

func DefaultMapGenSettings(w http.ResponseWriter, r *http.Request) {
WriteResponse(w, factorio.DefaultMapGenSettings())
}

func GenerateMapPreview(w http.ResponseWriter, r *http.Request) {
var resp interface{}
var mapGenSettingsFileName string
var mapSettingsFileName string
var previewImagePath string

defer func() {
if mapGenSettingsFileName != "" {
_ = os.Remove(mapGenSettingsFileName)
}
if mapSettingsFileName != "" {
_ = os.Remove(mapSettingsFileName)
}
if previewImagePath != "" {
_ = os.Remove(previewImagePath)
}
WriteResponse(w, resp)
}()

w.Header().Set("Content-Type", "application/json;charset=UTF-8")

body, resp, err := ReadRequestBody(w, r)
if err != nil {
return
}

var mapGenSettings factorio.MapGenSettings
mapGenSettings, resp, err = UnmarshallMapGenSettingsJson(body, w)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

mapGenSettingsFileName, resp, err = ParseSettingsAsFile(mapGenSettings)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

var mapSettings factorio.MapSettings
mapSettings, resp, err = UnmarshallMapSettingsJson(body, w)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

mapSettingsFileName, resp, err = ParseSettingsAsFile(mapSettings)

if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

previewImagePath, err = factorio.GenerateMapPreview(mapGenSettingsFileName, mapSettingsFileName)

if err != nil {
resp = fmt.Sprintf("Error creating map preview %s", err)
log.Println(resp)
w.WriteHeader(http.StatusInternalServerError)
return
}

previewImage, err := ioutil.ReadFile(previewImagePath)

if err != nil {
resp = fmt.Sprintf("Error read preview image %s", err)
log.Println(resp)
w.WriteHeader(http.StatusInternalServerError)
return
}

resp = "data:image/png;base64," + base64.StdEncoding.EncodeToString(previewImage)
}

func FactorioVersion(w http.ResponseWriter, r *http.Request) {
resp := map[string]string{}

Expand All @@ -435,6 +567,55 @@ func UnmarshallUserJson(body []byte, w http.ResponseWriter) (user User, resp int
return
}

func UnmarshallMapSettingsJson(body []byte, w http.ResponseWriter) (settings factorio.MapSettings, resp interface{}, err error) {
settings = factorio.DefaultMapSettings()
err = json.Unmarshal(body, &settings)
if err != nil {
resp = fmt.Sprintf("Unable to parse the request body: %s", err)
log.Println(resp)
w.WriteHeader(http.StatusBadRequest)
}
return
}

func UnmarshallMapGenSettingsJson(body []byte, w http.ResponseWriter) (settings factorio.MapGenSettings, resp interface{}, err error) {
settings = factorio.DefaultMapGenSettings()
err = json.Unmarshal(body, &settings)
if err != nil {
resp = fmt.Sprintf("Unable to parse the request body: %s", err)
log.Println(resp)
w.WriteHeader(http.StatusBadRequest)
}
return
}

func ParseSettingsAsFile(settings interface{}) (fileName string, resp interface{}, err error) {

var fileContent []byte
fileContent, err = json.MarshalIndent(settings, "", "")

if err != nil {
resp = fmt.Sprintf("Unable to parse the request body: %s", err)
return
}

var file *os.File
file, err = ioutil.TempFile("", "factorio-settings-file")

if err != nil {
resp = fmt.Sprint("Unable to create tmp file")
return
}

_, err = file.Write(fileContent)

if err != nil {
resp = fmt.Sprintf("Unable to write tmp file %s", file.Name())
return
}
return file.Name(), resp, err
}

// Handler for the Login
func LoginUser(w http.ResponseWriter, r *http.Request) {
var err error
Expand Down
24 changes: 23 additions & 1 deletion src/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ func NewRouter() *mux.Router {
Methods("GET").
Name("Saves").
Handler(http.StripPrefix("/saves", http.FileServer(http.Dir("./app/"))))
subRouter.Path("/map-generator").
Methods("GET").
Name("MapGenerator").
Handler(http.StripPrefix("/map-generator", http.FileServer(http.Dir("./app/"))))
subRouter.Path("/mods").
Methods("GET").
Name("Mods").
Expand Down Expand Up @@ -161,10 +165,28 @@ var apiRoutes = Routes{
false,
}, {
"CreateSave",
"GET",
"POST",
"/saves/create/{save}",
CreateSaveHandler,
true,
}, {
"GenerateMapPreview",
"POST",
"/saves/preview",
GenerateMapPreview,
true,
}, {
"DefaultMapSettings",
"GET",
"/saves/default-map-settings",
DefaultMapSettings,
false,
}, {
"DefaultMapGenSettings",
"GET",
"/saves/default-map-gen-settings",
DefaultMapGenSettings,
false,
}, {
"LoadModsFromSave",
"POST",
Expand Down
128 changes: 128 additions & 0 deletions src/factorio/mapGenSettings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package factorio

type MapResource struct {
Frequency float32 `json:"frequency"`
Size float32 `json:"size"`
Richness float32 `json:"richness"`
}

type AutoPlaceControls struct {
Coal MapResource `json:"coal"`
Stone MapResource `json:"stone"`
CopperOre MapResource `json:"copper-ore"`
IronOre MapResource `json:"iron-ore"`
UraniumOre MapResource `json:"uranium-ore"`
CrudeOil MapResource `json:"crude-oil"`
Trees MapResource `json:"trees"`
EnemyBase MapResource `json:"enemy-base"`
}

type CliffSettings struct {
Name string `json:"name"`
CliffElevation0 int `json:"cliff_elevation_0"`
CliffElevationInterval int `json:"cliff_elevation_interval"`
Richness int `json:"richness"`
}

type PropertyExpressionNames struct {
Elevation string `json:"elevation"`
MoistureFrequencyMultiplier string `json:"control-setting:moisture:frequency:multiplier"`
MoistureBias string `json:"control-setting:moisture:bias"`
AuxFrequencyMultiplier string `json:"control-setting:aux:frequency:multiplier"`
AuxBias string `json:"control-setting:aux:bias"`
}

type StartingPoints []struct {
X int `json:"x"`
Y int `json:"y"`
}

type MapGenSettings struct {
TerrainSegmentation int `json:"terrain_segmentation"`
Water int `json:"water"`
Width int `json:"width"`
Height int `json:"height"`
StartingArea float32 `json:"starting_area"`
PeacefulMode bool `json:"peaceful_mode"`
AutoPlaceControls AutoPlaceControls `json:"autoplace_controls"`

CliffSettings CliffSettings `json:"cliff_settings"`

PropertyExpressionNames PropertyExpressionNames `json:"property_expression_names"`

StartingPoints StartingPoints `json:"starting_points"`

Seed *int `json:"seed"`
}

func DefaultMapGenSettings() MapGenSettings {
return MapGenSettings{
TerrainSegmentation: 1,
Water: 1,
Width: 0,
Height: 0,
StartingArea: 1,
PeacefulMode: false,
AutoPlaceControls: AutoPlaceControls{
Coal: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
Stone: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
CopperOre: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
IronOre: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
UraniumOre: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
CrudeOil: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
Trees: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
EnemyBase: MapResource{
Frequency: 1,
Size: 1,
Richness: 1,
},
},
CliffSettings: CliffSettings{
Name: string("cliff"),
CliffElevation0: 10,
CliffElevationInterval: 40,
Richness: 1,
},
PropertyExpressionNames: PropertyExpressionNames{
MoistureFrequencyMultiplier: "1",
MoistureBias: "0",
AuxFrequencyMultiplier: "1",
AuxBias: "0",
},
StartingPoints: StartingPoints{
{
X: 0,
Y: 0,
},
},
Seed: nil,
}
}
Loading
Loading